问:
Structural pattern for an unconventional use of a database
I'm writing a game client as a personal project and using using it as a vehicle to learn about Java database access, specifically Neo4j, and possibly Spring Data Neo4j if I decide it's appropriate.  I'm well aware that my application is a bit unconventional, and this has raised questions that are hard frame narrowly.  I hope this question is appropriate for this site.

Maybe the best way to ask this is to first explain what I'm thinking of doing and why.  My main reason for incorporating a database is persistence, not queryability.  Because reaction times are critical, my plan is for the primary model of the game state to be an in-memory POJO graph.  I want to update the persistent database in an asynchronous, eventually-consistent way.  If I understand correctly, this is the reverse of most database applications, in which the database is authoritative and the in-memory data is just a snapshot copy.

Is there a name for this pattern?  If you've written something like this, what are some of the pitfalls I may encounter?  Is it naive to even try this?

答:
One pitfall is that if there is a power outage you will loose values which have not yet been persisted.

The architecture you describe is similar to that which commercial in-memory databases use (SAP Hana, Microsoft "Hekaton" etc.).  These address this problem by using efficient write-ahead logging.  You may be able to implement a version of that if data loss is not acceptable in your use case.


问:
What to do about "stopping point syndrome"?
I have noticed a behavior in myself that I call "stopping point syndrome"... it means I cannot stop working until I reach a "stopping point" (or I become exhausted).  In other words, if I am in the zone working on getting a feature completed, I won't stop until I get it done.   If it's a bug I'm working on, this effect is even more pronounced... I won't stop until it's fixed, or at the very least, understood.  Even though I work from a laptop and have VPN and could easily go home and pick up on the work later that evening, that fact does not help me leave work... it's like I'm afraid I will die before I find the bug.

I have a very hard time explaining this to family members who can't figure out why I never come home from work at the same time and sometimes come home at 11 pm.  Even managers have been mystified by this, and I've noticed that most of my colleagues have no trouble working the same hours every day.

Does anyone else have this problem?  Should I be worried about this and/or try to change it?  If so how?

答: I had this problem until I got dogs (two). I have to be home by a certain time or clean up urine, might not be what your are looking for but it works as a strong motivator. I also agree I almost always find the solution to be obvious in the morning.</p>

ContentLicense: CC BY-SA 2.5


答:
This is a fairly standard asynchronous programming pattern - I don't know if it has a name, but it is certainly the way that you might work with a lot of cloud solutions where you are working with NoSQL databases and most of the time you are dropping data into a queue from your application as it is updated and then expecting it will be persisted into the store when the application is ready. Most of the time data is only retrieved from the store when a new request begins or on application restart, so the in-memory model is the definitive one.

The thing that will help you out with this is knowing that you will probably want to use some kind of messaging queue to pass your data into the database- that should ensure that all your updates arrive and that they arrive in the correct order, but your front-end application can effectively drop things into the queue and forget about them. The data store then runs in its own process, picks queued items up and executes them whenever it can. This is also a really useful pattern to be aware of if you start looking at moving into distributed environments.

ContentLicense: CC BY-SA 3.0

Title: Structural pattern for an unconventional use of a database

Body:
I'm writing a game client as a personal project and using using it as a vehicle to learn about Java database access, specifically Neo4j, and possibly Spring Data Neo4j if I decide it's appropriate.  I'm well aware that my application is a bit unconventional, and this has raised questions that are hard frame narrowly.  I hope this question is appropriate for this site.

Maybe the best way to ask this is to first explain what I'm thinking of doing and why.  My main reason for incorporating a database is persistence, not queryability.  Because reaction times are critical, my plan is for the primary model of the game state to be an in-memory POJO graph.  I want to update the persistent database in an asynchronous, eventually-consistent way.  If I understand correctly, this is the reverse of most database applications, in which the database is authoritative and the in-memory data is just a snapshot copy.

Is there a name for this pattern?  If you've written something like this, what are some of the pitfalls I may encounter?  Is it naive to even try this?


问:
Where to place 3rd party software license information?
After a user installs my application, where in the app's install directory should I place information regarding 3rd party software (e.g. FOSS) licenses? Should I just append it to my EULA? Is there some sort of convention or standard that I should following to make it easily scan-able by license detection scripts?</p>

答:
You probably ought to do both - place it in your EULA as well as providing a LICENSE.txt (or equivalent) file.  That way, your end users are aware of the licenses prior to accepting the terms of your license as well as being able to go back and reference the licenses later.

Most packages place the LICENSE.txt file in the application root folder, but to my knowledge there's nothing preventing you from putting it in a logical place.  If there's a convention, it's to place the file in the root of the application folder.

If you have a large number of licenses, then you may want to create a folder underneath your application called Licenses and list all of the applicable licenses.


问:
Make Return Type an Interface - Problem with Initialization
I would like to make the return type of my method an interface rather than a class for similar reasons stated in  c# List or IList, however I am having trouble figuring out how to initialize the interface to return it.  I cannot use new IA() and (IA) new A() does not work as I cannot cast the result to B.

```<code>interface IA{}
class A: IA{}
class B: IA{}

class UseIA
{
  public IA DesiredMethod()
  {
    return ???;// new IA()
  }
  public A UndesiredMethod()
  {
    return new A();
  }
}
</code>```

答:
Just a small expansion on @Kaan's post.  This is to point out polymorphism, since the O.P. has two classes implementing one interface.

```<code>interface IA { }
class A : IA { }
class B : IA { }

class UseIA
{
    public IA DesiredMethod()
    {
        return new A;   // let's say, for the purposes of the exercise, that class A is the default implementation of IA
    }

    public IA DesiredMethod(String whichImplementationOfIA)   // overloaded method
    {
        switch (whichImplementationOfIA)
        {
            case "GiveMeA": return new A();
            case "GiveMeB": return new B();
            default:
                throw new ArgumentException();     // or, alternatively, return A, because it's a default implementation in this exercise
        }
    }
}
</code>```

By the way, the second scenario (where an argument specifies which class will be created) is reminiscent of Class Factory patterns.

Body:
Just a small expansion on @Kaan's post.  This is to point out polymorphism, since the O.P. has two classes implementing one interface.

interface IA { }
class A : IA { }
class B : IA { }

class UseIA
{
    public IA DesiredMethod()
    {
        return new A;   // let's say, for the purposes of the exercise, that class A is the default implementation of IA
    }

    public IA DesiredMethod(String whichImplementationOfIA)   // overloaded method
    {
        switch (whichImplementationOfIA)
        {
            case "GiveMeA": return new A();
            case "GiveMeB": return new B();
            default:
                throw new ArgumentException();     // or, alternatively, return A, because it's a default implementation in this exercise
        }
    }
}

By the way, the second scenario (where an argument specifies which class will be created) is reminiscent of Class Factory patterns.


问:
Which Continuous Integration framework do you use and why?
There are quite a few different Continuous Integration (CI) frameworks out there and I'm wondering which is the most popular.  Which frameworks have you used at firms where you work?

Is there any reason one CI framework is more popular than another - perhaps this is to do with the features it offers, things that integrate into it or maybe its just marketing?

It seems like continuous integration is used more in the Java and .net worlds than say ruby or python.  Why is this?

答:
Personally, I've only ever used CruiseControl and CruiseControl.Net.  The reason for this has to do with economics.  They are reasonably stable and once you set them up, there really is little you need to do to maintain it.  The user community is usually very helpful, and it can be extended to your needs.

That said, there are a couple commercial offerings available that I am aware of (one by JetBrains, the other by Atlassian) which offer a better set up experience and commercial support.  I've been meaning to try these offerings but really haven't had a chance yet.

CI tools have a more important role to play with compiled languages than interpreted languages, but that isn't to say that the CI tool is wasted on interpreted languages.  When you have several projects that depend on each other, and you want to make sure a change doesn't accidentally break it's dependencies--CI tools are invaluable.

There's three general classes of problems that CI tools can help you catch:

Compile errors -- if the signature of a class changes in a way that breaks dependencies, it's best to know about it before the waining hours of a deliverable.

Logic errors -- if the behavior of a class changes in a way that breaks dependencies, it's best to know about it early.  This has to be checked by some sort of automated testing, most commonly unit testing.

Acceptance Testing -- if you have an automated suite of tests to run on the finished product, it's best to run them often.

Interpreted languages are not compiled, so there are no compilation errors to catch.  However, the other two problems are common enough that CI tools are useful for projects in Ruby/Python/Perl/etc.

The key word in both the logic errors and acceptance testing points is "automated" testing.  If you don't have a suite of tests a machine can run, then you really are missing the greater benefits of CI tools.  Automated suites can be built up with time, so you can start small.

Edit

See this nice chart for feature comparisons of a large number of CI Tools (many of which I didn't know about):

http://confluence.public.thoughtworks.org/display/CC/CI+Feature+Matrix


答:
The point of declaring an interface as the return type is not to actually return something with only an interface type. You can't, since interfaces can't be instantiated. The point is to make the contract of your method more explicit: "I'm returning something with a doA() method, but not necessarily a classic StandardA object. I might be switching to a SecretSuperDuperA object some day, and you wouldn't know the difference. All you know is that whatever I return will have the doA() method you need."

In other words, it allows the implementation writer more latitude how to do the job of the method best, while still ensuring that the caller actually gets the specific bit of functionality that they need.

Title: Make Return Type an Interface - Problem with Initialization

Body:
I would like to make the return type of my method an interface rather than a class for similar reasons stated in  c# List or IList, however I am having trouble figuring out how to initialize the interface to return it.  I cannot use new IA() and (IA) new A() does not work as I cannot cast the result to B.

```<code>interface IA{}
class A: IA{}
class B: IA{}

class UseIA
{
  public IA DesiredMethod()
  {
    return ???;// new IA()
  }
  public A UndesiredMethod()
  {
    return new A();
  }
}
</code>```


问:
What should be done on git while migrating new distribution and packet manager?
In the project I am working, we are using Freebsd and we are creating our software packages for it.

Now we are planning to change distribution to Centos and rpm for packet manager. Since our codes are not platform independent, we have to make many change on it. Also we will continue to use freebsd until migration is completed.

What is the best git usage way for this type of migration. Should we use a new branch or a new repository?

答:
The projects under Git, will you need to redesign the fundamental architecture because of this migration? If a project changes fundamentally in such a way that the new iteration is like a completely new project, then it makes sense to create a new Git repository for it.

If there won't be a fundamental redesign, only relatively superficial modifications, for example porting tools, shell scripts, Makefiles from BSD to GNU, but the architecture / framework /skeleton of the project staying basically the same, then it probably makes more sense to create a branch instead.


问:
Is splitting up a function into several inner functions an anti-pattern?
Imagine a long and complicated process, which is started by calling function foo(). There are several consecutive steps in this process, each of them depending on result of the previous step. The function itself is, say, about 250 lines. It is highly unlikely that these steps would be useful on their own, not as a part of this whole process.

Languages such as Javascript allow creating inner functions inside a parent function, which are inaccessible to outer functions (unless they are passed as a parameter).

A colleague of mine suggest that we can split up the content of foo() into 5 inner functions, each function being a step. These functions are inaccessible to outer functions (signifying their uselessness outside of the parent function). The main body of foo() simply calls these inner function one by one:

```<code>foo(stuff) {
    var barred = bar(stuff);
    var bazzed = baz(barred);
    var confabulated = confabulate(bazzed);
    var reticulated = reticulate(confabulated);
    var spliced = splice(reticulated);

    return spliced;

    // function definitions follow ...
}
</code>```

Is this an anti-pattern of some sort? Or is this a reasonable way to split up long functions? Another question is: is this acceptable when using OOP paradigm in Javascript? Is it OK to split an object's method this way, or does this warrant another object, which contains all these inner functions as private methods?

See also:

Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else? - a previous question of mine, which leads into this one.

@KilianFoth's answer to a very similar question which provides a different perspective compared to the answers given here.

答:
It's not an anti-pattern. It's the right way to do it.

It's easier to read, to maintain, to test. It helps avoid duplication.

See : clean code (the bible for devs) and this answer


答:
Inner functions are not an anti-pattern, they are a feature.

If it doesn't make sense to move the inner functions outside, then by all means, don't.

On the other hand, it would be a good idea to move them outside so you can unit test them easier. (I don't know if any framework lets you test inner functions.) When you have a function with 250+ lines, and you make any changes in the logic, are you sure you're not breaking anything? You really need unit tests there, and it won't be feasible with one giant function.

Splitting up long functions to smaller ones is a good idea in general. It's a common refactoring technique to replace a comment with a function named after the comment, called "extract method". So yes, do it!

As @Kilian pointed out, see also this related post:

Should I place functions that are only used in one other function, within that function?

Title: Is splitting up a function into several inner functions an anti-pattern?

Body:
Imagine a long and complicated process, which is started by calling function foo(). There are several consecutive steps in this process, each of them depending on result of the previous step. The function itself is, say, about 250 lines. It is highly unlikely that these steps would be useful on their own, not as a part of this whole process.

Languages such as Javascript allow creating inner functions inside a parent function, which are inaccessible to outer functions (unless they are passed as a parameter).

A colleague of mine suggest that we can split up the content of foo() into 5 inner functions, each function being a step. These functions are inaccessible to outer functions (signifying their uselessness outside of the parent function). The main body of foo() simply calls these inner function one by one:

```<code>foo(stuff) {
    var barred = bar(stuff);
    var bazzed = baz(barred);
    var confabulated = confabulate(bazzed);
    var reticulated = reticulate(confabulated);
    var spliced = splice(reticulated);

    return spliced;

    // function definitions follow ...
}
</code>```

Is this an anti-pattern of some sort? Or is this a reasonable way to split up long functions? Another question is: is this acceptable when using OOP paradigm in Javascript? Is it OK to split an object's method this way, or does this warrant another object, which contains all these inner functions as private methods?

See also:

Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else? - a previous question of mine, which leads into this one.

@KilianFoth's answer to a very similar question which provides a different perspective compared to the answers given here.


问:
Quickly compute added and removed lines
I'm trying to compare two text files. I want to compute how many lines were added and removed. Basically what git diff --stat is doing. Bonus points for not having to store the entire file contents in memory.

The approach I'm currently having in mind is:

read each line of the old file

compute a hash (probably MD5 or SHA-1) for each line

store the hashes in a set

do the same for each line in the new file

every hash from the old file set that's missing in the new file set was removed

every hash from the new file set that's missing in the old file set was added

I'll probably want to exclude empty and all white space lines. There is a small issue with duplicated lines. This can either be solved by additionally storing how often a hash appears or comparing the number of lines in the old and new file and adjust either the added or removed lines so that the numbers add up.

Do you see room for improvements or a better approach?

Edit

I'm currently using Java and the SVNKit library.

答:
why not do this:

read each line of the old file

there's no 2

store the lines in a set

do the same for each line in the new file

every line from the old file set that's missing in the new file set was removed

every line from the new file set that's missing in the old file set was added

I don't see any need to calculate hashes, if you're going to compare things you might as well compare actual lines.

Title: Quickly compute added and removed lines


问:
How to develop cross platform mobile applications with native UI and Javascript backend?
I want to build a cross platform(Android, iOS, Windows) mobile application.

I want the UX of the application to be different on the different platforms so that it will be more platform specific and does not force different platform users to stick to a common UI, as this common UI might not gel well in terms of look and feel with other native applications in their platform.
However since it is the same application that I am trying to build across all platforms my backend will mostly be the same.

This image presents what I am trying to achieve.

Is it possible to build different UI for each platform using native technologies like Storyboard(in iOS), XML(in Android), XAML(in Windows)
and then bind these UI elements to native controllers.
And making this controller use a common javascript backend for all the platforms.

I am aware of the concept of Native and Hybrid applications.
The problem that I would face with them are the following

Pure native applications will force me to make the entire source code platform specific which will make me write my backend thrice in 3 different languages. (Least reusable)

Hybrid applications(like those build on PhoneGap) will let me write my code in javascript and html but will create a common ui with HTML5/CSS3 which should be used across all platforms, I want to have different UI and for the UI to be more native than generic.

Is this common javascript backend code achievable.
And if it is then is there a way in which I can create this entire javascript code independently and package it as platform specific libraries like .a(for iOS), .jar(for Android), .dll(for Windows).
Or should I use some other approach?

Thanks in Advance

答: There are a couple of frameworks supporting this kind of thing -- Calatrava is Javascript/Coffescript focussed, or if you prefer to code your backend in Java look at Kirin (which I have worked on and worked with extensively).  Check out my answer to this question for more information.</p>


答:
It's not an anti-pattern, but it's a questionable move. If those functions are not valuable outside their parent function, there is no benefit of separating them, just more code. You could just put some comments in code saying "now we confabulate previously buzzed thingy", and it would have same value in less lines of code.

EDIT: I'd rephrase my answer, because I've used not very careful wording there, and, apparently, community didn't accept it, based on downvotes. What I really wanted to say is that one should take  into account the amount of extra code and attention breaks while reading. When the original function is small enough (how small is opinion-based), it could be easier to read it as one stream of text with some helping comments, than jumping back and forth between inner functions. It could easily be that one chunk of code is easier to read and understand than a collection of several functions.

On the other hand, when the original function is big enough to understand as one piece, it totally makes sense to split it. Principle of lesser scope definitely comes into play here. It's just important to understand when the function is "big enough" for that. It's easy to make such judgement when the original one is 10k LOC, as was commented, but what about the OP's example, 250 LOC? I'd say it's becoming opinion-based to give as an answer.


问:
Kerberos for key management?
We have half-implemented proper key management at our dev shop. We have a SOAP web service (the key management web service) that can be used to retrieve passwords for other systems. So for instance, I might make a request to this service for the password to, say, a production PostgreSQL DB. I hit the web service with my AD credentials, and it determines whether I'm authorized to receive the DB password or not. If I am, then it is sent in the response. I can then use this service across all other software components instead of storing the DB password in a static config file (like Tomcat's context.xml, etc.).

The problem, of course, is that with an automated process the AD credentials passed into the web service need to be stored somewhere. So, to obtain the password to a DB (or any other secured resource), one simply needs to gain access to what is used to store the AD credentials, and can then submit them to this web service, which will then authenticate/authorize them, and return the password for the requested resource. Classic key management problem.

Hence, I'm trying to figure out a way to protect the AD credentials used to access the service. Someone mentioned Kerberos to me and I've began to dig in a little bit.

My understanding is that, with Kerberos, there would be 3 components:

A client of the key management web service

The key management web service

A Kerberos (ticket granting ticket, TGT) server

My understanding is that:

The client (somehow) obtains a TGT from Kerberos

The client then issues a a request for some resource, say, a DB, to the key management web service, but does not supply any AD credentials, but instead, supplies the TGT

The key management web service is then reconfigured to take this TGT and ping the Kerberos server with an "is this TGT valid?"-type request

The Kerberos server responds and says "yes" (or "no") and honors the request for the DB password, sending it back to the client in the response

So first, if anything about my understanding is incorrect, please begin by correcting me!

Assuming I'm more-or-less correct, then I have a few questions about this setup:

How would the client first obtain the TGT from Kerberos?

Do Kerberos TGT's have expiration dates? How would then client "re-request" a new TGT?

Does the key management web service need to implement any specific TCP protocol to speak with Kerberos, or does HTTP suffice? If Kerberos has its own protocol, are there any Java libs that implement it? (I know its easy to Google "java kerberos" but not sure what specifically to be looking for because again, I'm not confident I understand the architecture here).

答:
The client obtains a TGT (=ticket granting ticket) by sending credentials to the kerberos server.

And now this is the point where I see the first major problem. You need some credentials. Is there really enough advantage in having credentials A just so you can request credentials B that you actually need instead of having credentials B in the first place? One credentials or or other credentials. I don't see how it would solve any problem.

Ok, so you sent credentials to the Kerberos server and received your ticket. You then use GSSAPI in the other protocol to authenticate yourself using your ticket and the service will ask kerberos what permissions it should grant you.

Well, so now you have credentials A that you pass to service W (kerberos), get credentials B (the ticket), you pass that to service X, get credentials C (which is again username and password, presumably) and use that to request the actual service Y. Now that is an extra step and didn't really bring any benefit still. Fortunately you can get rid of that extra step. The service Y almost certainly can do GSSAPI too.  PostgreSQL certainly does as does any Microsoft thing, because the authentication part of Active Domain is kerberos. So you can replace X with kerberos instead. You ask kerberos for a ticket and then just use that ticket to access the database.

So we are back at using credential A to request credential B, just replaced your in-house thing with industry standard. If you need credential A in the application configuration, we just gained absolutely nothing. There may be two advantages depending on other conditions:

You can use the same credentials for multiple services. That does not have any real benefit for credentials stored in config file, but it has big advantage for credentials provided by the user. So if the credentials A come from a user, you want to do this, so the user only needs one username and password.

The password is not sent in clear-text to the database server. If the connection is not encrypted and there is a risk of it being sniffed, then it is a point. But in such case you probably want to avoid the data being sniffed too, in which case you need SSL anyway and cleartext password in SSL is not a problem.

Technical details are too broad. Either you need to ask specifically (setting up kerberos authentication in language X using library Y etc.; that kind of questions should belong on Stack Overflow, not here) or you need to read the documentation.

Title: Kerberos for key management?


答:
The most important issue is to manage complexity. Inner methods are one of the solutions, but I'm not convinced that a best one.

You want to split the method because it's long, but with inner methods the method is still long, just divided into "chapters". It's better than "comment chapters", though.

A better solution is to use an inner class that gathers all of the helper methods and - what is also important - data. Additionally, this class can be unit tested separately.

This is a variation of Fowler's "Replace Method with Method Object" refactoring.


问:
How to log configuration or code behaviour changes in non-disruptive way
We've probably all been in the situation where you'd like to alert your team members to some change ("I changed X, so now it's running every hour instead of every day"). But the change is non-urgent, and email can be disruptive - or get tuned out.

Anyone have any techniques where the team can have a running log of changes that everyone should be aware of, that they can peruse at their leisure - or at least, when they suspect something is up?

答: In our team we do code reviews with Gerrit now, and since we started it became easier to keep everyone in the loop about code changes. The team is relatively small, and everyone reviews everyone others changes, so the awareness of them is quite high. We've agreed to start a day with code reviews, and code doesn't go to master branch before being reviewed, so usually there's a push from the code's author to get his change merged, and the review process doesn't stuck. I guess, introducing a code review might be a too big change in your development process to take this as an answer, but this definitely helps.</p>


答:
I guess you could do this quite simply with Appcelerator Titanium.

http://www.appcelerator.com/

This framework lets you write code in Javascript and it compiles it native code. So you can have for instance a Navbar which will be rendered natively by iOS, Android and so on.

Title: How to develop cross platform mobile applications with native UI and Javascript backend?

Body:
I want to build a cross platform(Android, iOS, Windows) mobile application.

I want the UX of the application to be different on the different platforms so that it will be more platform specific and does not force different platform users to stick to a common UI, as this common UI might not gel well in terms of look and feel with other native applications in their platform.
However since it is the same application that I am trying to build across all platforms my backend will mostly be the same.

This image presents what I am trying to achieve.

Is it possible to build different UI for each platform using native technologies like Storyboard(in iOS), XML(in Android), XAML(in Windows)
and then bind these UI elements to native controllers.
And making this controller use a common javascript backend for all the platforms.

I am aware of the concept of Native and Hybrid applications.
The problem that I would face with them are the following

Pure native applications will force me to make the entire source code platform specific which will make me write my backend thrice in 3 different languages. (Least reusable)

Hybrid applications(like those build on PhoneGap) will let me write my code in javascript and html but will create a common ui with HTML5/CSS3 which should be used across all platforms, I want to have different UI and for the UI to be more native than generic.

Is this common javascript backend code achievable.
And if it is then is there a way in which I can create this entire javascript code independently and package it as platform specific libraries like .a(for iOS), .jar(for Android), .dll(for Windows).
Or should I use some other approach?

Thanks in Advance


问:
Java: method takes varargs of unrelated types
I have a Java factory method with a varargs array of Objects at the end.  The array can contain any combination of Strings and ScaledJpegs.  The theory being that an HTML table cell can contain any number of text nodes or <image> nodes and it will line-wrap the images as though they were just funny-shaped words.

```<code>// constructor
public Cell(TextStyle ts, float w, CellStyle cs, Object... r) {
    if (w < 0) {
        throw new IllegalArgumentException("A cell cannot have a negative width");
    }
    if (r != null) {
        for (Object o : r) {
            if ( (o != null) &&
                 !(o instanceof String) &&
                 !(o instanceof ScaledJpeg) ) {
                throw new IllegalArgumentException(INVALID_ROW_TYPE_STR);
            }
        }
    }
    textStyle = ts; width = w; cellStyle = cs; rows = r;
    avgCharsForWidth = (int) ((width * 1220) / textStyle.avgCharWidth());
}
</code>```

In Scala, I might use a list of Either[String,ScaledJpeg].  But some day I'll probably make this method allow something else, say another nested Cell, but doing so would break existing code that only expected two possible types.  At least the way it is, future changes won't break existing code.

The current solution works, allows for expansion, and is relatively easy to use, except that it defeats type safety and can only throw an exception at runtime if someone passes something unexpected as a vararg.  For instance, I just forgot to add toString() to a StringBuilder and it blew up at runtime.  So already that's a third class to account for (Since toString() is defined on every object, I don't want to call it on whatever is passed because doing so for most object types would be an error much further down in the code violating the fail-fast behavior of this example).

java.lang.String can't implement any new interfaces and that's probably a good thing.  Even if I could make a wrapper class, everything about the way text and images are treated by this class is completely different except that they are line-wrapped together the way they would be in HTML (or in a Word doc).

As I write this, it occurs to me that I should probably use a Builder pattern, make a CellBuilder class that has addText() and addImage() methods that does away with the varargs constructor.  This would encapsulate the underlying List in a way that the user of the API gets 100% compile-time type safety.  But out of curiosity, I'm still posting this in case there are other creative and possibly better solutions out there.

答:
Since you assign rows = r and r: Array[Object], I'd use this approach:

```<code>sealed trait HasRow {
  def row: Object
}

class StringRow(s: String) extends HasRow {
  override def row = s // or some logic
}

class JpegRow(j: ScaledJpeg) extends HasRow {
  override def row = j // or some logic
}

class Cell(ts: TextStyle, w: Float, cs: CellStyle, r: HasRow*) {
 // ...
}
</code>```

As you mention, a builder style approach is also possible and might be better.

Body:
Since you assign rows = r and r: Array[Object], I'd use this approach:

sealed trait HasRow {
  def row: Object
}

class StringRow(s: String) extends HasRow {
  override def row = s // or some logic
}

class JpegRow(j: ScaledJpeg) extends HasRow {
  override def row = j // or some logic
}

class Cell(ts: TextStyle, w: Float, cs: CellStyle, r: HasRow*) {
 // ...
}

As you mention, a builder style approach is also possible and might be better.


答:
```<code> >  what are some of the pitfalls ?
</code>```

your app is not scalable. in other words: you cannot use a cloud/cluster to improve performance by adding more servers, if you have to many (thousands of) simultanious users.

As long as the number of users is limited so that the "in memory graph" can be handled with one server it is ok.

Body:
 >  what are some of the pitfalls ?

your app is not scalable. in other words: you cannot use a cloud/cluster to improve performance by adding more servers, if you have to many (thousands of) simultanious users.

As long as the number of users is limited so that the "in memory graph" can be handled with one server it is ok.


答:
I think this type of code can be easily be converted to a chaining.
Like this :

```<code>foo(stuff)
{
  return
    stuff
      .bar()
      .baz()
      .confabulate()
      .reticulate()
      .splice()
}
</code>```

From my humble point of view, it's easy to read, keeps the separation of concern and limit the error rate (if one of the step fails, all the process fail).

Body:
I think this type of code can be easily be converted to a chaining.
Like this :

foo(stuff)
{
  return
    stuff
      .bar()
      .baz()
      .confabulate()
      .reticulate()
      .splice()
}

From my humble point of view, it's easy to read, keeps the separation of concern and limit the error rate (if one of the step fails, all the process fail).


问:
What are the warning signs of impending doom to watch out for on a project?
Having worked on a failed project is one of the few things that most programmers have in common, regardless of language used, industry or experience.

These projects can be great learning experiences, soul-crushing disasters (or both!), and can occur for a multitude of reasons:

upper management change of heart

under-skilled / under-resourced team

emergence of superior competitor during dev cycle

over/under management

Once you've worked on a couple of such projects, is it possible to recognise at an early stage exactly when a project is doomed to fail?

For me, a big sign is having a hard & fast external deadline combined with feature creep. I've seen projects which were well planned out and proceeding right on schedule go horribly off the rails once the late feature requests started to roll in and get added to the final "deliverable". The proposers of these requests earned the nickname of Columbo, due to rarely leaving the room without asking for "just one more thing".

What are the warning signs you look out for that set off the alarm bells of impending doom in your head?

答: You're "90% done", the delivery is next week, but it's ok because all you have left is "testing".</p>


答: What you want is a Row interface with two implementations:  one for images and one for strings.  Then your Cell constructor takes a Row... r.  This lets the compiler verify your types, and keeps you from having if image... else if string... all over the place.  Adding a new type is simple, just create another implementation.  If you need a new method in the interface, your compiler ensures all your implementations have it.

Title: Java: method takes varargs of unrelated types

Body:
I have a Java factory method with a varargs array of Objects at the end.  The array can contain any combination of Strings and ScaledJpegs.  The theory being that an HTML table cell can contain any number of text nodes or <image> nodes and it will line-wrap the images as though they were just funny-shaped words.

```<code>// constructor
public Cell(TextStyle ts, float w, CellStyle cs, Object... r) {
    if (w < 0) {
        throw new IllegalArgumentException("A cell cannot have a negative width");
    }
    if (r != null) {
        for (Object o : r) {
            if ( (o != null) &&
                 !(o instanceof String) &&
                 !(o instanceof ScaledJpeg) ) {
                throw new IllegalArgumentException(INVALID_ROW_TYPE_STR);
            }
        }
    }
    textStyle = ts; width = w; cellStyle = cs; rows = r;
    avgCharsForWidth = (int) ((width * 1220) / textStyle.avgCharWidth());
}
</code>```

In Scala, I might use a list of Either[String,ScaledJpeg].  But some day I'll probably make this method allow something else, say another nested Cell, but doing so would break existing code that only expected two possible types.  At least the way it is, future changes won't break existing code.

The current solution works, allows for expansion, and is relatively easy to use, except that it defeats type safety and can only throw an exception at runtime if someone passes something unexpected as a vararg.  For instance, I just forgot to add toString() to a StringBuilder and it blew up at runtime.  So already that's a third class to account for (Since toString() is defined on every object, I don't want to call it on whatever is passed because doing so for most object types would be an error much further down in the code violating the fail-fast behavior of this example).

java.lang.String can't implement any new interfaces and that's probably a good thing.  Even if I could make a wrapper class, everything about the way text and images are treated by this class is completely different except that they are line-wrapped together the way they would be in HTML (or in a Word doc).

As I write this, it occurs to me that I should probably use a Builder pattern, make a CellBuilder class that has addText() and addImage() methods that does away with the varargs constructor.  This would encapsulate the underlying List in a way that the user of the API gets 100% compile-time type safety.  But out of curiosity, I'm still posting this in case there are other creative and possibly better solutions out there.


问:
Should I parse XML on the server or provide a proxy and let the browser parse it?
I need to interface with a 3rd party API. With this API I make a GET request from within the end user's browser and receive an XML response. This data is to be used in a browser based application where the user can search through it, use it to make decisions, etc. The main issue is that most browsers have locked down cross-domain XML use, so I can't simply get the XML from the API.

The overall data, though, is basically broken into two sets.

The first set of data is public and only needs to be updated every so often, so it can be cached for all users on the server side, lightening the traffic considerably.

The second set of data is private and individual to each user. This data is also updated in the API more frequently. This leads caching to be much less effective.

For scalability reasons I would like to keep the server's load a small as possible.

I see two options before me:

Provide a proxy that can be used to route XML requests to the 3rd party server and directly back and forth between client and 3rd party API.

Have the server do the conversion from XML to JSON and strip out unnecessary information. This essentially means making a new API for our server, which translates into requests from the 3rd party API

What would be the best way to provide the data to the user? (Does not have to be one of the two options)

答:
For scalability reasons I would like to keep the server's load a small as possible

I think this is more or less pointing to the answer. Whether or not providing preprocessed data to the client or not depends mainly on:

the difference with regard to traffic

the performance impact of the processing

the impact of a different data format on the client

If the XML is comparingly small or there are only a few requests, it may make sense to just forward it to the client and forget it. Same is true when the preprocessed data are still a large part of the original data, or if the client is not able to profit much from a different data format (say JSON, for example).

However, if the client struggles with processing a large XML data set, or if the client needs only a small fraction of the original XML data, then it may make sense to do some preprocessing on the server side.

At the end, it is easier to scale a server, than it is to scale a client/browser or the available bandwidth. To put it in one sentence, it depends on where the bottleneck is in the system.


答:
Yes, splitting is good, may it only be for better readabilty and testability.

Another approach might be to call the functions within each other, you start with:

```<code>foo(stuff) {
   var spliced = splice(stuff);
   return spliced;
}
</code>```

Since the spliced function needs reticulated data, you can call that function first:

```<code>splice(stuff) {
    var reticulated = reticulate(stuff);
    //do splicing of reticulated
    return spliced;
}
</code>```

So all functions would pass stuff through and work with the results they receive.

Body:
Yes, splitting is good, may it only be for better readabilty and testability.

Another approach might be to call the functions within each other, you start with:

foo(stuff) {
   var spliced = splice(stuff);
   return spliced;
}

Since the spliced function needs reticulated data, you can call that function first:

splice(stuff) {
    var reticulated = reticulate(stuff);
    //do splicing of reticulated
    return spliced;
}

So all functions would pass stuff through and work with the results they receive.


答:
The proxy option is the easiest one to implement. You don't have any custom development to do, the only thing to do is to set up a proxy. It's also straightforward: there is no additional code to maintain, and if the API changes, you have no changes to make on your side.

A proxy would be a preferred choice:

If you need to ship working software fast. This makes it a good choice, for example, if you were about to ship a feature, but found during the implementation phase of the project that you can't just make cross-domain AJAX requests.

Or if the current API is well designed: the architecture is good, the calls are very clear, the documentation is complete and easy to understand.

Or if the current API is subject to change. If it changes, you just need to change the JavaScript implementation. If instead of a proxy, you are parsing the results and generating your own JSON, there is a risk that the changes to the API will require the changes in your server-side code.

On the other hand, parsing the result has a benefit to make it possible to abstract completely the API on client-side. This is a slower alternative, since it requires to design the new interface (if the original API is not well designed) and to implement the extract, transform and load features, but it may be a good long-term choice for a large project. This is a preferred choice:

If you need additional features. You can exploit the different features which weren't available in the original API, such as caching on a level which is not supported by an ordinary proxy server, or encryption, or a different authentication model.

For example, if the number of AJAX requests becomes an issue or if two-ways communication model makes sense, you can implement Web Sockets.

Or if the current API is not well designed. Like a facade pattern, this approach enables you to redesign the API. If the original one is poor, having a facade makes it possible to solve the bad design choices made by the original authors of a legacy API. You can act as well on large parts, such as the overall architecture of the API, but also on details, such as the names of arguments or the error messages.

While modifying an existent API is sometimes impossible, having a facade can make it possible to work with a piece of clean code which abstracts the drawbacks and errors in the original design.

Or if the current API is subject to change. Indeed, you may prefer to change server-side code instead of JavaScript if the API changes over time, while keeping the public interface of your facade unaffected. It may be easier either because you're more experienced with server-side programming or because you know more tools for server-side refactoring or because it's easier in your project to deal with server-side code versioning.

You may notice that I omitted talking about JSON, performance, caching, etc. There is a reason for that:

JSON vs. XML: it's up to you to pick the right technology. You do it by measuring objectively the overheat of XML over JSON, the time it takes to serialize data and the ease of parsing.

Performance: benchmark different implementations, pick the fastest one, then profile it and optimize it based on the results from the profiler. Stop when you achieve the performance specified in the non-functional requirements.

Also, understand what are you trying to achieve. There are several parts interacting with each other: the original API, the bandwidth between your server and the API's one, the performance of your server, the bandwidth between your server and the end users and the performance of their machines. If you're asked to obtain a response to a request within 30 ms., but the original API spends 40 ms. processing the request, no matter what you do, you won't be able to obtain the required performance.

Caching: caching is one of the techniques to make your web application feeling faster, reducing bandwidth, etc.

Make sure you use client caching as well (server-side caching won't reduce bandwidth usage between you and the customers), given that setting up the HTTP headers properly is often tricky.

Make sure you determine correctly what to cache, for how long and when to invalidate it: if the description of the product changed 10 seconds ago, but the customers of an e-commerce website still see the old version, it's OK. If the owner changed the description, submitted it, and still sees the previous variant because of the caching, this is problematic.

Don't focus only on caching. Minification, for example, is important as well. Reducing the number of requests can also be beneficial.

Title: Should I parse XML on the server or provide a proxy and let the browser parse it?

Body:
I need to interface with a 3rd party API. With this API I make a GET request from within the end user's browser and receive an XML response. This data is to be used in a browser based application where the user can search through it, use it to make decisions, etc. The main issue is that most browsers have locked down cross-domain XML use, so I can't simply get the XML from the API.

The overall data, though, is basically broken into two sets.

The first set of data is public and only needs to be updated every so often, so it can be cached for all users on the server side, lightening the traffic considerably.

The second set of data is private and individual to each user. This data is also updated in the API more frequently. This leads caching to be much less effective.

For scalability reasons I would like to keep the server's load a small as possible.

I see two options before me:

Provide a proxy that can be used to route XML requests to the 3rd party server and directly back and forth between client and 3rd party API.

Have the server do the conversion from XML to JSON and strip out unnecessary information. This essentially means making a new API for our server, which translates into requests from the 3rd party API

What would be the best way to provide the data to the user? (Does not have to be one of the two options)


问:
Is this proper OO design for C++?
I recently took a software processes course and this is my first time attempting OO design on my own. I am trying to follow OO design principles and C++ conventions. I attempted and gave up on MVC for this application, but I am trying to "decouple" my classes such that they can be easily unit-tested and so that I can easily change the GUI library used and/or the target OS. At this time, I have finished designing classes but have not yet started implementing methods.

The function of the software is to log all packets sent and received, and display them on the screen (like WireShark, but for one local process only). The software accomplishes this by hooking the send() and recv() functions in winsock32.dll, or some other pair of analogous functions depending on what the intended Target is. The hooks add packets to SendPacketList/RecvPacketList. The GuiLogic class starts a thread which checks for new packets. When new packets are found, it utilizes the PacketFilter class to determine the formatting for the new packet, and then sends it to MainWindow, a native win32 window (with intent to later port to Qt).1

Full size image of UML class diagram

Here are my classes in skeleton/header form (this is my actual code):

```<code>class PacketModel
{
protected:
    std::vector<byte> data;
    int id;
public:
    PacketModel();
    PacketModel(byte* data, unsigned int size);
    PacketModel(int id, byte* data, unsigned int size);
    int GetLen();
    bool IsValid(); //len >= sizeof(opcode_t)
    opcode_t GetOpcode();
    byte* GetData(); //returns &(data[0])
    bool GetData(byte* outdata, int maxlen);
    void SetData(byte* pdata, int len);
    int GetId();
    void SetId(int id);
    bool ParseData(char* instr);
    bool StringRepr(char* outstr);
    byte& operator[] (const int index);
};

class SendPacket : public PacketModel
{
protected:
    byte* returnAddy;
public:
    byte* GetReturnAddy();
    void SetReturnAddy(byte* addy);
};

class RecvPacket : public PacketModel
{
protected:
    byte* callAddy;
public:
    byte* GetCallAddy();
    void SetCallAddy(byte* addy);
};

//problem: packets may be added to list at any time by any number of threads
//solution: critical section associated with each packet list
class Synch
{
public:
    void Enter();
    void Leave();
};

template<class PacketType> class PacketList
{
private:
    static const int MAX_STORED_PACKETS = 1000;
public:
    static const int DEFAULT_SHOWN_PACKETS = 100;
private:
    vector<PacketType> list;
    Synch synch; //wrapper for critical section
public:
    void AddPacket(PacketType* packet);
    PacketType* GetPacket(int id);
    int TotalPackets();
};

class SendPacketList : PacketList<SendPacket>
{

};

class RecvPacketList : PacketList<RecvPacket>
{

};

class Target //one socket
{
    bool Send(SendPacket* packet);
    bool Inject(RecvPacket* packet);
    bool InitSendHook(SendPacketList* sendList);
    bool InitRecvHook(RecvPacketList* recvList);
};

class FilterModel
{
private:
    opcode_t opcode;
    int colorID;
    bool bFilter;
    char name[41];
};

class FilterFile
{
private:
    FilterModel filter;
public:
    void Save();
    void Load();
    FilterModel* GetFilter(opcode_t opcode);
};

class PacketFilter
{
private:
    FilterFile filters;
public:
    bool IsFiltered(opcode_t opcode);
    bool GetName(opcode_t opcode, char* namestr); //return false if name does not exist
    COLORREF GetColor(opcode_t opcode); //return default color if no custom color
};

class GuiLogic
{
private:
    SendPacketList sendList;
    RecvPacketList recvList;
    PacketFilter packetFilter;
    void GetPacketRepr(PacketModel* packet);
    void ReadNew();
    void AddToWindow();
public:
    void Refresh(); //called from thread
    void GetPacketInfo(int id); //called from MainWindow
};
</code>```

I'm looking for a general review of my OO design, use of UML, and use of C++ features. I especially just want to know if I'm doing anything considerably wrong.

From what I've read, design review is on-topic for this site (and off-topic for the Code Review site).

Any sort of feedback is greatly appreciated. Thanks for reading this.

答:
Naming is important

What is a SendPacket? How is it different to a RecvPacket? Surely sending and receiving are operations performed on packets, rather than types of packet?

For that matter, what is a PacketModel? It looks like a packet, unless there's some metadata I don't see. Is it supposed to store the byte contents of one packet, or somehow describe a type of packet?

If packets are the same type regardless of whether you're sending or receiving them, you only need one type of list to contain them.

What does Target mean? It's a really generic word - is it supposed to represent a network host/peer/IP address, or an IP+port, or some internal observer, or something else? In a comment you say it's a Socket - so why not just call it a Socket?

It isn't clear why you Send a SendPacket but Inject a RecvPacket. Where do you inject it? If it is supposed to be a received packet injected by the script engine, then Target is a mixture of an abstract socket - which is a source of incoming packets and a destination for outgoing packets - and some scripted mock socket. That seems like a potentially useful distinction.

Make your abstractions flexible

Your current PacketList is your interface to the GUI, which presumably has its own thread, but you've made it impossible to use a good callback/signalling mechanism. The GUI has to either block or busy-wait calling GetPacket on each list sequentially. This is either inefficient, or guaranteed to be unresponsive, or possibly both.

It would be better to have a callback mechanism to the GUI, so an implementation can choose the best way to dispatch and synchronize events to the GUI thread on a given platform (although you need to work out how to manage the lifetime of these packet objects).

Couple carefully

Why is your FilterModel coupled to the GUI - is because you're mainly using it to colour packets? This appears to prevent you discarding packets you're not interested in before passing them up to the GUI, which seems wasteful.

Specifics

I'm not sure what all the addy stuff is supposed to accomplish - you could just expose a const ref to the underlying vector. That would be safer (unless you want to allow modification of received packet data), and cleaner. I'm also not sure what StringRepr is supposed to do - writing into an un-checked char*? Either pass a buffer size so you can check for overflow, or better implement a std::ostream& operator<< (std::ostream&, Packet const &) and let the stream worry about overflows and memory management.

Title: Is this proper OO design for C++?


问:
Just jumped into database testing in PHPUnit - not really sure what the purpose of it is
I've been reading about database testing in PHPUnit. I'm not exactly sure what it's purpose is. Should I use this to test schema? E.g. if I have a UNIQUE email column then ensure that I'm not allow duplicate email addresses? (I shouldn't put this in my class tests then?)

Is there anything else? I've been reading through documentation, blog posts etc trying to get my head round it .. it's also 2am, perhaps I need to sleep on it too :) Would appreciate if someone could explain in simple terms what this type of testing sets out to do.

答:
Databases are not very different from code:

They should always be under version control. This rule is essential for any team of one or more developers.

Databases are versioned similarly to code.

Databases require architecture, design and implementation.

More time is spent maintaining databases than creating them.

Databases should be tested.

If you have written unit tests to test your application, imagine database tests as the same thing, but for databases: instead of testing the logic of your code, they focus on the database itself and how it handles the data.

Similarly to the application itself which can hold complex business logic with multiple, complex rules, database rules can become particularly complex in large applications. A database may contain:

Constraints, which have to be tested just like any other code. Check constraints, for example, may become quite difficult over time, but even the simplest constraints such as the maximum length of a field or an unique constraint should be tested as well if the database is holding business-critical data.

Queries, for example in a form of a view. When views start to do inner joins, groupings, etc., it's time to test them as well.

Code, for example in stored procedures. Projects which use stored procedures a lot and have large ones are not unusual. One way is to verify that those stored procedures contain code which is purely related to database, and doesn't contain business logic: often, they contain business logic which then can be moved outside the database. Sometimes, this is not possible; in that case, this code should at least be thoughtfully tested.

Features, such as Unicode support. Complex features are tricky, and you may expect the database to behave in one way, while it does the opposite. A basic example from the list below: if one of your applications handles Unicode normalization forms, another one doesn't, and the database doesn't either, you may find yourself loading two products with an exact same name, while you expect the names to be unique.

Let's take an example of a table which stores products. Here are some database tests which may exist:

Ensure that the name of the product can contain a maximum of 100 characters.

Tested feature: length constraints.

Ensure that Unicode names are inserted and selected correctly.

Tested feature: Unicode support.

Ensure that the name of the product can contain a maximum of 100 Unicode characters.

Tested feature: length constraints coupled with Unicode support.

Ensure that it is impossible to insert two products with the same name.

Tested feature: unique constraint.

Ensure that it is impossible to insert two products with the same Unicode name written using different Unicode normalization forms.

Tested feature: complex case mixing unique constraints and Unicode support.

Ensure it is impossible to insert a product without a name.

Tested feature: non-NULL constraint (and eventually a check constraint).

Ensure that the product cannot be created without being assigned to at least one category.

Tested feature: check constraint.

Ensure that the price in RebateProductsView is determined as expected based on a sample product with a specified price and rebate.

Tested feature: view.

Ensure that the price in RebateProductsView is still determined correctly when the product price is equal to zero.

Tested feature: view.

Ensure that it is possible to store 5.000.000 products.

Tested feature: scalability.

Ensure that a given select takes less than 4 ms. in 95% of tested cases on a given machine when the table contains 1.000.000 products.

Tested feature: performance.

Ensure that when inserting a product with the price 13.95 while the database default culture is fr-FR where the correct way to write it would be 13,95 produces the expected result.

Tested feature: encoding.


问:
What is the name of λx.λf.fx (like reverse apply) in lambda calculus? Does the corresponding function have a standard name in programming?
What is the name of λx.λf.fx in lambda calculus?

Does the corresponding function have a standard name in functional programming languages, like Haskell?

In object oriented programming, is there a usual name for a method foo which takes a function as an argument, such that x.foo(f) returns f(x)?

答:
This is sometimes referred to as the thrush combinator, and in Clojure it's called the thread-first macro. It's primary use is in allowing you to express a computation as a series of chained computations in the order they execute in. For instance, taking a value x, passing it to a function f, then passing the results of f(x) to a function g, would be written as g(f(x)) using standard function composition (or g (f x) if you're working with implicit parentheses.) This can be awkward when there's a large number of chained functions because you have to read them in the reverse order of how they execute. The thrush combinator lets you express this differently, if we define the thrush combinator as:

```<code>T x f = f x
T x f g ... = T (T x f) g ...
</code>```

Then the expression T x f g h becomes h (g (f x)).

(For those looking for more information as well as a concrete implementation in the language Racket, I have a blog post on the subject: Thrush Combinator in Racket)

Body:
This is sometimes referred to as the thrush combinator, and in Clojure it's called the thread-first macro. It's primary use is in allowing you to express a computation as a series of chained computations in the order they execute in. For instance, taking a value x, passing it to a function f, then passing the results of f(x) to a function g, would be written as g(f(x)) using standard function composition (or g (f x) if you're working with implicit parentheses.) This can be awkward when there's a large number of chained functions because you have to read them in the reverse order of how they execute. The thrush combinator lets you express this differently, if we define the thrush combinator as:

T x f = f x
T x f g ... = T (T x f) g ...

Then the expression T x f g h becomes h (g (f x)).

(For those looking for more information as well as a concrete implementation in the language Racket, I have a blog post on the subject: Thrush Combinator in Racket)


问:
Writing a superset of a programming language as a transcompiler
My idea is to write a superset of C# (but question is not language-specific), so that it source-to-source compiles (transcompiles) to C# itself (fall-through switch clauses, default method parameters etc., nothing impossible in C#).

First idea was to parse it, make syntax trees, abstract trees etc. but it seems as a bit of an overkill to me, mostly because large portions of code will remain the same.

My question: Is there a simpler way to do this?

One of my ideas was to search for tokens that need modifying (e.g. switch in case of fall-through) and then rewrite the code (add goto case NEXT_CASE where needed) but is there a better and cleaner way to do this?

答:
One simpler way which actually matches your idea with searching tokens etc. is called preprocessor

It is a piece of "transcompiler" which is quite easy to write as it actually does not understand the language semantics and sometimes it even does not understand the language syntax, except few basics (like tokenizing the input source). It operates just on the text level. In order to "compile" into valid target code, some strict syntax rules must be usually obeyed by the programmers.

There has been quite a few preprocessors in the history, e.g. macro assembler or perhaps the best known the C preprocessor

Out of the less known and very powerful I have quite admired the one used by Alaska, the successor of the Clipper programming language.

The preprocessor was able to handle most of the syntactic sugar and most of the Clipper-compatibility things.

It is definitely easier to implement and as long as the language superset will be used only by programmers who can be made to follow some rules - you should get the thing done (or at least have a 1st working prototype) in a reasonable time


问:
Cleanest way to report errors in Haskell
I'm working on learning Haskell, and I've come across three different ways of dealing with errors in functions I write:

I can simply write error "Some error message.", which throws an exception.

I can have my function return Maybe SomeType, where I may or may not be able to return what I'd like to return.

I can have my function return Either String SomeType, where I can return either an error message or what I was asked to return in the first place.

My question is: Which method of dealing with errors should I use, and why? Maybe I should different methods, depending on the context?

My current understanding is:

It's "difficult" to deal with exceptions in purely functional code, and in Haskell one wants to keep things as purely functional as possible.

Returning Maybe SomeType is the proper thing to do if the function will either fail or succeed (i.e., there aren't different ways it can fail).

Returning Either String SomeType is the proper thing to do if a function can fail in any one of various ways.

答:
I wouldn't separate 2 and 3 based on how many ways something can fail. As soon as you think there's only one possible way, another will show its face. The metric should instead be "do my callers care why something failed? Can they actually do anything about it?".

Beyond that, it's not immediately clear to me that Either String SomeType can produce an error condition.  I would make a simple algebraic data type with the conditions with a more descriptive name.

Which you use depends on the nature of the problem you face, and the idioms of the software package you're working with. Though I would tend to avoid #1.


问:
Which management book would you recommend to read for a fresh Team Leader?
Which management book would you recommend to read for a fresh Team Leader?</p>

答:
Managing Humans, aka the collection of managerial stuff from Rands In Repose, is worth the read, and funny to boot.

A ton of truth concentrated down to its essence.


答:
Alright, first rule of error handling in Haskell: Never use error.

It's just terrible in every way. It exists purely as an act of history and the fact that Prelude uses it is terrible. Don't use it.

The only conceivable time you could use it is when something is so internally terrible that something must be wrong with the very fabric of reality, thus rendering the outcome of your program moot.

Now the question becomes Maybe vs Either. Maybe is nicely suited to something like head, which may or may not return a value but there is only one possible reason to fail. Nothing is saying something like "it broke, and you already know why". Some would say it indicates a partial function.

The most robust form of error handling is Either + an error ADT.

For example in one of my hobby compilers, I have something like

```<code>data CompilerError = ParserError ParserError
                   | TCError TCError
                   ...
                   | ImpossibleError String

data ParserError = ParserError (Int, Int) String
data TCError = CouldntUnify Ty Ty
             | MissingDefinition Name
             | InfiniteType Ty
             ...

type ErrorM m = ExceptT CompilerError m -- from MTL
</code>```

Now I define a bunch of error types, nesting them so that I have one glorious top level error. This can be an error from any stage of compilation or an ImpossibleError, which signifies a compiler bug.

Each of these error types try to keep as much information for as long as possible for pretty printing or other analysis. More importantly, by not having a string I can test that running an illtyped program through the type checker actually generates a unification error! Once something is a String, it's gone forever and any information it contained is opaque to the compiler/tests, so just Either String isn't great either.

Finally I pack this type into ExceptT, a new monad transformer from MTL. This is essentially EitherT and comes with a nice batch of functions for throwing and catching errors in a pure, pleasant way.

Finally, it's worth mentioning that Haskell has the mechanisms to support handling exceptions like other languages do, except that catching an exception lives in IO. I know some people like to use these for IO heavy applications where everything could potentially fail, but so infrequently that they don't like to think about it. Whether you use these impure exceptions or just ExceptT Error IO is really a matter of taste. Personally I opt for ExceptT because I like being reminded of the chance of failure.

As a summary,

Maybe - I can fail in one obvious way

Either CustomType - I can fail, and I'll tell you what happened

IO + exceptions - I sometimes fail. Check my docs to see what I throw when I do

error - I hate you too user

Title: Cleanest way to report errors in Haskell

Body:
I'm working on learning Haskell, and I've come across three different ways of dealing with errors in functions I write:

I can simply write error "Some error message.", which throws an exception.

I can have my function return Maybe SomeType, where I may or may not be able to return what I'd like to return.

I can have my function return Either String SomeType, where I can return either an error message or what I was asked to return in the first place.

My question is: Which method of dealing with errors should I use, and why? Maybe I should different methods, depending on the context?

My current understanding is:

It's "difficult" to deal with exceptions in purely functional code, and in Haskell one wants to keep things as purely functional as possible.

Returning Maybe SomeType is the proper thing to do if the function will either fail or succeed (i.e., there aren't different ways it can fail).

Returning Either String SomeType is the proper thing to do if a function can fail in any one of various ways.

Body:
Alright, first rule of error handling in Haskell: Never use error.

It's just terrible in every way. It exists purely as an act of history and the fact that Prelude uses it is terrible. Don't use it.

The only conceivable time you could use it is when something is so internally terrible that something must be wrong with the very fabric of reality, thus rendering the outcome of your program moot.

Now the question becomes Maybe vs Either. Maybe is nicely suited to something like head, which may or may not return a value but there is only one possible reason to fail. Nothing is saying something like "it broke, and you already know why". Some would say it indicates a partial function.

The most robust form of error handling is Either + an error ADT.

For example in one of my hobby compilers, I have something like

data CompilerError = ParserError ParserError
                   | TCError TCError
                   ...
                   | ImpossibleError String

data ParserError = ParserError (Int, Int) String
data TCError = CouldntUnify Ty Ty
             | MissingDefinition Name
             | InfiniteType Ty
             ...

type ErrorM m = ExceptT CompilerError m -- from MTL

Now I define a bunch of error types, nesting them so that I have one glorious top level error. This can be an error from any stage of compilation or an ImpossibleError, which signifies a compiler bug.

Each of these error types try to keep as much information for as long as possible for pretty printing or other analysis. More importantly, by not having a string I can test that running an illtyped program through the type checker actually generates a unification error! Once something is a String, it's gone forever and any information it contained is opaque to the compiler/tests, so just Either String isn't great either.

Finally I pack this type into ExceptT, a new monad transformer from MTL. This is essentially EitherT and comes with a nice batch of functions for throwing and catching errors in a pure, pleasant way.

Finally, it's worth mentioning that Haskell has the mechanisms to support handling exceptions like other languages do, except that catching an exception lives in IO. I know some people like to use these for IO heavy applications where everything could potentially fail, but so infrequently that they don't like to think about it. Whether you use these impure exceptions or just ExceptT Error IO is really a matter of taste. Personally I opt for ExceptT because I like being reminded of the chance of failure.

As a summary,

Maybe - I can fail in one obvious way

Either CustomType - I can fail, and I'll tell you what happened

IO + exceptions - I sometimes fail. Check my docs to see what I throw when I do

error - I hate you too user


问:
GPL and non GPL software common installer
From my vague understanding of this subject I assumed that if I make an installer for my program and it contains a GPL library my code would have to fall under GPL. However, I noticed yesterday when installing Ubuntu that its installation had checkboxes (selected by default) to install non free software.

This question specifies about programming behavior and says that my program wouldn't fall under GPL as long as the library can be seem as separated programs but it does not say anything about making a common installer for the package.

I saw this answer saying about common installers in StackOverflow in Portuguese and it does say about a common installer making the code fall under GPL.

If I create an installer for the library and put my non-free program that uses that library there as an option my program wouldn't fall under GPL ?

答:
The part of the GPL FAQ which says

We believe that a proper criterion [for drawing a line between two separate programs] depends both on the mechanism of communication [...]  and the semantics of the communication.

is IMHO really clear - putting separate GPL and non-GPL programs in one installation package has nothing to do with communication between those programs. So this fact alone is no criteria for enforcing GPL on a non-GPL software.

Furthermore, the GNU GPL FAQ says:

The installer and the files it installs are separate works.
  As a result, the terms of the GPL do not apply to the installation software.

This means not even the installer has to be GPL when used for packaging GPL modules (and why should other non-GPL modules in the same package become "GPL" when not even the installer has to?).

However, you are talking about

a non-free program that uses that [GPL] library

and not about

a non-free program that uses a [GPL] software through pipes, sockets or a command-line interface

So, when your program uses a GPL library (by linking against it), the GPL will apply and you have to put your own program under GPL due to the fact you are using a standard linking mechanism, but not to the fact you put those modules into the same installation package.


问:
Why are inheritance and polymorphism so widely used?
The more I learn about different programming paradigms, such as functional programming, the more I begin to question the wisdom of OOP concepts like inheritance and polymorphism.  I first learned about inheritance and polymorphism in school, and at the time polymorphism seemed like a wonderful way to write generic code that allowed for easy extensibility.

But in the face of duck typing (both dynamic and static) and functional features such as higher-order functions, I've begun to look at inheritance and polymorphism as imposing an unnecessary restriction based on a fragile set of relationships between objects.  The general idea behind polymorphism is that you write a function once, and later you can add new functionality to your program without changing the original function - all you need to do is create another derived class which implements the necessary methods.

But this is a lot simpler to achieve through duck typing, whether it's in a dynamic language like Python, or a static language like C++.

As an example, consider the following Python function, followed by its static C++ equivalent:

```<code>def foo(obj):
   obj.doSomething()

template <class Obj>
void foo(Obj& obj)
{
   obj.doSomething();
}
</code>```

The OOP equivalent would be something like the following Java code:

```<code>public void foo(DoSomethingable obj)
{
  obj.doSomething();
}
</code>```

The major difference, of course, is that the Java version requires the creation of an interface or an inheritance hierarchy before it will work.  The Java version thus involves more work, and is less flexible.  Additionally, I find that most real-world inheritance hierarchies are somewhat unstable.  We've all seen the contrived examples of Shapes and Animals, but in the real world, as business requirements change and new features are added, it's difficult to get any work done before you need to really stretch the "is-a" relationship between sub-classes, or else remodel/refactor your hierarchy to include further base-classes or interfaces in order to accommodate new requirements.  With duck typing, you don't need to worry about modeling anything - you just worry about the functionality you need.

Yet, inheritance and polymorphism are so popular that I doubt it would be much of an exaggeration to call them the dominant strategy for extensibility and code reuse.  So why are inheritance and polymorphism so wildly successful?  Am I overlooking some serious advantages that inheritance/polymorphism have over duck typing?

答:
Inheritance, even when reason from a FP perspective, is a great concept; it not only saves a lot of time, it gives meaning to the relation between certain objects in you program.

```<code>public class Animal {
    public virtual string Sound () {
        return "Some Sound";
    }
}

public class Dog : Animal {
    public override string Sound () {
        return "Woof";
    }
}

public class Cat : Animal {
    public override string Sound () {
        return "Mew";
    }
}

public class GoldenRetriever : Dog {

}
</code>```

Here the class GoldenRetriever has the same Sound as Dog for free thank's to inheritance.

I'll write the same example with my level of Haskell for you to see the difference

```<code>data Animal = Animal | Dog | Cat | GoldenRetriever

sound :: Animal -> String
sound Animal = "Some Sound"
sound Dog = "Woof"
sound Cat = "Mew"
sound GoldenRetriever = "Woof"
</code>```

In here you don't escape having to specify sound for GoldenRetriever. The easiest thing in general would be to

```<code>sound GoldenRetriever = sound Dog
</code>```

but just imagen if you have 20 functions! If there is a Haskell expert please show us an easier way.

That said, it would be great to have pattern matching and inheritance at the same time, where a function would default to the base class if the current instance doesn't have the implementation.

Body:
Inheritance, even when reason from a FP perspective, is a great concept; it not only saves a lot of time, it gives meaning to the relation between certain objects in you program.

public class Animal {
    public virtual string Sound () {
        return "Some Sound";
    }
}

public class Dog : Animal {
    public override string Sound () {
        return "Woof";
    }
}

public class Cat : Animal {
    public override string Sound () {
        return "Mew";
    }
}

public class GoldenRetriever : Dog {

}

Here the class GoldenRetriever has the same Sound as Dog for free thank's to inheritance.

I'll write the same example with my level of Haskell for you to see the difference

data Animal = Animal | Dog | Cat | GoldenRetriever

sound :: Animal -> String
sound Animal = "Some Sound"
sound Dog = "Woof"
sound Cat = "Mew"
sound GoldenRetriever = "Woof"

In here you don't escape having to specify sound for GoldenRetriever. The easiest thing in general would be to

sound GoldenRetriever = sound Dog

but just imagen if you have 20 functions! If there is a Haskell expert please show us an easier way.

That said, it would be great to have pattern matching and inheritance at the same time, where a function would default to the base class if the current instance doesn't have the implementation.


答: My choice would be to cache and compress (throw away unnecessary information) and gzip results to the client browser, your option #2. Because browsers are not usually high-end CPUs and the server to browser network lines are of limited capacity. I'm talking about mobile clients. If you don't plan to support mobile clients then choose whatever is simpler, e.g. some Google:CORS proxy


问:
How can a statically typed language support duck typing?
I understand what dynamic and static type systems are, and what duck typing is. But I don't understand how you can have a static language that supports duck typing. To my understanding only a dynamically typed language can support duck typing.

This answer from StackOverflow explains that "Duck typing is something that is completely orthogonal to static, dynamic, weak, or strong typing." It gives an example from C++ for duck typing in a statically typed language, but I'm not a C++ programmer and I don't understand it.

I'd like an explanation of how it's possible for a static language to support duck typing.

答:
In my experience, it is simply a language that uses static typing with a Structural Type System. It essentially applies the "walks like a duck, talks like a duck" check at compile type so that the programmer doesn't need to provide annotations to specifically sub-type things.

This has a very large benefit when you're trying to glue two (or more) libraries together. With a nominative type system, if you had some interface in one library and an object in the other, they don't know about one another and can't sub-type - even if the object satisfies the interface's requirements. Structural typing makes that okay.

Making the language static just means that the compiler does that check at compile time, giving you an error early (and clearly) when that object doesn't really satisfy the interface.

There are a few esoteric languages that do this, but most structurally typed languages are also dynamically typed and almost all nominative typed languages are also statically typed.


答:
If the code shown below compiled in a language that otherwise resembled C, then this fictitious language would presumably exhibit "static" duck typing (according to Wikipedia, at least):</p>

```<code>typedef struct s1{
 int a;
 int b;
};

typedef struct s2{
 int a;
 int b;
};

s1 thing1;
s1.a=1;
s1.b=2;

s2 thing2;
thing2=thing1; //This is where a "real" C compiler would complain
</code>```

Title: How can a statically typed language support duck typing?

Body:
I understand what dynamic and static type systems are, and what duck typing is. But I don't understand how you can have a static language that supports duck typing. To my understanding only a dynamically typed language can support duck typing.

This answer from StackOverflow explains that "Duck typing is something that is completely orthogonal to static, dynamic, weak, or strong typing." It gives an example from C++ for duck typing in a statically typed language, but I'm not a C++ programmer and I don't understand it.

I'd like an explanation of how it's possible for a static language to support duck typing.

Body:
If the code shown below compiled in a language that otherwise resembled C, then this fictitious language would presumably exhibit "static" duck typing (according to Wikipedia, at least):

typedef struct s1{
 int a;
 int b;
};

typedef struct s2{
 int a;
 int b;
};

s1 thing1;
s1.a=1;
s1.b=2;

s2 thing2;
thing2=thing1; //This is where a "real" C compiler would complain


答:
The usual meaning of such a term is just structural typing.

In structurally typed systems, things have a static type. However that type is based on the actual structure of the type rather than any particular type name.

For example, let's say we have the Python code

```<code>def foo(bar):
  bar.baz()
  bar.quux(5)
</code>```

Now it's not clear what the type of bar is, but whatever it is we know

It has a method baz which takes no arguments

It has a method quux which takes 1 integer argument

Now in a structural type system we could assign foo a type

```<code>foo : forall a b. r{baz : () -> a, quux : (int) -> b} -> Void
</code>```

where that funny r thing means

Any type r which the methods ...

Many languages implement some subset of structurally typed features, C++ for example implements "structural typing" via templates. However this is a slightly adhoc approach.

Other languages implement row-types. These are just structurally typed records/structs! Types where we can say something like "we want a record with at least the fields ...". I believe purescript implements these.

Go has something like structural types with it's "implicit interfaces". These are just interfaces that a type implements automagically. However this isn't full structural types since it doesn't allow for a structural type to be handled parametrically, that is there's no way to say something like

```<code>foo :: r{a : int} -> w{a : int} -> r
foo r w = w -- Type error!!
</code>```

Since everything is "upcasted" to an interface, rather than merely treated opaquely.

There's been some talk of adding these to Haskell view -XOverloadedRecordFields, but I'm not aware of any real progress on structural typing in it's full generality.

Body:
The usual meaning of such a term is just structural typing.

In structurally typed systems, things have a static type. However that type is based on the actual structure of the type rather than any particular type name.

For example, let's say we have the Python code

def foo(bar):
  bar.baz()
  bar.quux(5)

Now it's not clear what the type of bar is, but whatever it is we know

It has a method baz which takes no arguments

It has a method quux which takes 1 integer argument

Now in a structural type system we could assign foo a type

foo : forall a b. r{baz : () -> a, quux : (int) -> b} -> Void

where that funny r thing means

Any type r which the methods ...

Many languages implement some subset of structurally typed features, C++ for example implements "structural typing" via templates. However this is a slightly adhoc approach.

Other languages implement row-types. These are just structurally typed records/structs! Types where we can say something like "we want a record with at least the fields ...". I believe purescript implements these.

Go has something like structural types with it's "implicit interfaces". These are just interfaces that a type implements automagically. However this isn't full structural types since it doesn't allow for a structural type to be handled parametrically, that is there's no way to say something like

foo :: r{a : int} -> w{a : int} -> r
foo r w = w -- Type error!!

Since everything is "upcasted" to an interface, rather than merely treated opaquely.

There's been some talk of adding these to Haskell view -XOverloadedRecordFields, but I'm not aware of any real progress on structural typing in it's full generality.


答:
Do you know Typescript?

It may seem as a simplistic example but here it goes: it's a language that compiles to Javascript. Now, Javascript itself is dynamically and duck typed, but let's just forget about JS for a second.

Typescript supports static typing, meaning that it will check if your types are correct during compilation and spit out warnings if it thinks you may have made an error. (You can follow up the tutorial and it will show you an example of this)

However, even if it supports static typing, it also has the whole JS duck typing thing. You can use var all around the place, omitting the types Typescript adds and the code will compile and run.

So, it's statically typed, but you can go quack-quack, too. It will even check the quack-quack for you if you let it.

Duck typing is for your typing convenience and in some languages for having generics (such as C++). Static typing is for checking the types you have specified during compilation, if you're working on a compiled language.


答:
Statically typed just means the types are checked at compile time.  It's just as easy for a compiler to check that a type has a method with a certain name and signature as it is to check that a type is a part of a specific inheritance hierarchy.  The trick is finding a concise way to specify "this argument to this function is any type that has a method with this specific name."

The method I'm most familiar with to accomplish this is using a type class, which is a declaration that basically says, "any type that implements all these functions can be referred to using this name."

Usually you must specifically declare a type to be an instance of a type class, but it doesn't have to be in the same code that the type itself is defined, which means anyone can add their own type class after the fact to types they don't control.  That's sort of a compromise to total duck typing, more like, "if it walks like a duck and quacks like a duck, then anyone anywhere can explicitly declare it a duck-like thing, and everyone else can treat it like a duck."

However, it's not that big of a stretch to allow types to be implicitly added to a type class, you just lose a bit of control.  As Amon and Jozefg pointed out, the go language has interfaces which basically act like implicitly added type classes.


问:
Keep user and user profile in different tables?
I have seen in a couple of projects that developers prefer to keep essential user info in one table (email/login, password hash, screen name) and rest of the non essential user profile in another (creation date, country, etc). By non-essential I mean that this data is needed only occasionally. Obvious benefit is that if you are using ORM querying less fields is obviously good. But then you can have two entities mapped to same table and this will save you from querying stuff you don't need (while being more convenient). Does anybody know any other advantage of keeping these things in two tables?</p>

答:
My main reason to keep them separate is to try and avoid what's known in Object Oriented programming as a 'god class'.  ORM's relate tables and fields to classes and attributes, so it becomes relevant as the SQL level too (even without an ORM there's a similar principle at play generally).

The User class (and by association the user table) is frequently the table that becomes the god class with hundred of attributes/fields, dozens or hundreds of methods and a class definition (for the methods) of over 1000 lines.  I've seen it all.  More than once.

So the separation out of user tries to address that.  There may be person, user, account and the separation of concerns may seem a bit artificial but it is to try and avoid complexity and ensure that each object is only concerned about 1 aspect of the data.


问:
Is splitting up a function into several inner functions an anti-pattern?
Imagine a long and complicated process, which is started by calling function foo(). There are several consecutive steps in this process, each of them depending on result of the previous step. The function itself is, say, about 250 lines. It is highly unlikely that these steps would be useful on their own, not as a part of this whole process.

Languages such as Javascript allow creating inner functions inside a parent function, which are inaccessible to outer functions (unless they are passed as a parameter).

A colleague of mine suggest that we can split up the content of foo() into 5 inner functions, each function being a step. These functions are inaccessible to outer functions (signifying their uselessness outside of the parent function). The main body of foo() simply calls these inner function one by one:

```<code>foo(stuff) {
    var barred = bar(stuff);
    var bazzed = baz(barred);
    var confabulated = confabulate(bazzed);
    var reticulated = reticulate(confabulated);
    var spliced = splice(reticulated);

    return spliced;

    // function definitions follow ...
}
</code>```

Is this an anti-pattern of some sort? Or is this a reasonable way to split up long functions? Another question is: is this acceptable when using OOP paradigm in Javascript? Is it OK to split an object's method this way, or does this warrant another object, which contains all these inner functions as private methods?

See also:

Is it OK to split long functions and methods into smaller ones even though they won't be called by anything else? - a previous question of mine, which leads into this one.

@KilianFoth's answer to a very similar question which provides a different perspective compared to the answers given here.

答:
It is certainly better to keep each "inner function" separate: small, combinable parts are much easier to maintain than monolithic "big balls of mud". Be careful with your terminology though: functions and methods aren't the same thing, from a stylistic point of view.

Methods tend to favour one object ("this") above others, which limits their usefulness to that object. Functions are independent of any particular value, which makes them more flexible and easier to combine together.

In this case, your "foo" function is clearly the composition of those "internal functions", so you might as well define it that way and avoid all of the intermediate boilerplate ("stuff", "barred", "bazzed", "confabulated", "reticulated", "spliced", "function(stuff) {" and "return ...; }"):

```<code>var foo = [splice, reticulate, confabulate, baz, bar].reduce(compose, id);
</code>```

If you haven't already got "compose" and "id" functions, here they are:

```<code>var compose = function(f, g) { return function(x) { return f(g(x)); }; };
var id = function(x) { return x; };
</code>```

Congratulations, you've just gained two incredibly useful, reusable parts out of the supposedly "useless" internals of foo. I can't do much more without seeing the definitions of the "internal" functions, but I'm sure there's more simplification, generalisation and reusability available waiting to be discovered.

Body:
It is certainly better to keep each "inner function" separate: small, combinable parts are much easier to maintain than monolithic "big balls of mud". Be careful with your terminology though: functions and methods aren't the same thing, from a stylistic point of view.

Methods tend to favour one object ("this") above others, which limits their usefulness to that object. Functions are independent of any particular value, which makes them more flexible and easier to combine together.

In this case, your "foo" function is clearly the composition of those "internal functions", so you might as well define it that way and avoid all of the intermediate boilerplate ("stuff", "barred", "bazzed", "confabulated", "reticulated", "spliced", "function(stuff) {" and "return ...; }"):

var foo = [splice, reticulate, confabulate, baz, bar].reduce(compose, id);

If you haven't already got "compose" and "id" functions, here they are:

var compose = function(f, g) { return function(x) { return f(g(x)); }; };
var id = function(x) { return x; };

Congratulations, you've just gained two incredibly useful, reusable parts out of the supposedly "useless" internals of foo. I can't do much more without seeing the definitions of the "internal" functions, but I'm sure there's more simplification, generalisation and reusability available waiting to be discovered.


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
Aside from the theory answers listed, often this gets used in the context of too clever for everyone else.

Move between a top tier performance intensive team and a medium tier maintenance team sometime to see the real life differences in what is "too clever".

Leaving out the theory arguments, too clever is often based on what the least skilled team members can work with reasonably, so it is very relative to the environment.