问:
Why does Java not do type inference?
I have always wondered why Java does not do type inference given that the language is what it is, and its VM is very mature. Google's Go is an example of a language with excellent type inference and it reduces the amount of typing one has to do. Is there any special reason behind this feature not being a part of Java?</p>

答:
Technically speaking, Java does have type inferencing when using generics. With a generic method like

```<code>public <T> T foo(T t) {
  return t;
}
</code>```

The compiler will analyze and understand that when you write

```<code>// String
foo("bar");
// Integer
foo(new Integer(42));
</code>```

A String is going to be returned for the first call and an Integer for the second call based on what was input as an argument. You will get the proper compile-time checking as a result. Additionally, in Java 7, one can get some additional type inferencing when instantiating generics like so

```<code>Map<String, String> foo = new HashMap<>();
</code>```

Java is kind enough to fill in the blank angle brackets for us. Now why doesn't Java support type inferencing as a part of variable assignment? At one point, there was an RFE for type inferencing in variable declarations, but this was closed as "Will not fix" because

Humans benefit from the redundancy of the type declaration in two ways.
  First, the redundant type serves as valuable documentation - readers do
  not have to search for the declaration of getMap() to find out what type
  it returns.
  Second, the redundancy allows the programmer to declare the intended type,
  and thereby benefit from a cross check performed by the compiler.

The contributor who closed this also noted that it just feels "un-java-like", which I am one to agree with. Java's verbosity can be both a blessing and a curse, but it does make the language what it is.

Of course that particular RFE was not the end of that conversation. During Java 7, this feature was again considered, with some test implementations being created, including one by James Gosling himself. Again, this feature was ultimately shot down.

With the release of Java 8, we now get type inference as a part of lambdas as such:

```<code>List<String> names = Arrays.asList("Tom", "Dick", "Harry");
Collections.sort(names, (first, second) -> first.compareTo(second));
</code>```

The Java compiler is able to look at the method Collections#sort(List<T>, Comparator<? super T>) and then the interface of Comparator#compare(T o1, T o2) and determine that first and second should be a String thus allowing the programmer to forgo having to restate the type in the lambda expression.

Title: Why does Java not do type inference?

Body:
Technically speaking, Java does have type inferencing when using generics. With a generic method like

public <T> T foo(T t) {
  return t;
}

The compiler will analyze and understand that when you write

// String
foo("bar");
// Integer
foo(new Integer(42));

A String is going to be returned for the first call and an Integer for the second call based on what was input as an argument. You will get the proper compile-time checking as a result. Additionally, in Java 7, one can get some additional type inferencing when instantiating generics like so

Map<String, String> foo = new HashMap<>();

Java is kind enough to fill in the blank angle brackets for us. Now why doesn't Java support type inferencing as a part of variable assignment? At one point, there was an RFE for type inferencing in variable declarations, but this was closed as "Will not fix" because

Humans benefit from the redundancy of the type declaration in two ways.
  First, the redundant type serves as valuable documentation - readers do
  not have to search for the declaration of getMap() to find out what type
  it returns.
  Second, the redundancy allows the programmer to declare the intended type,
  and thereby benefit from a cross check performed by the compiler.

The contributor who closed this also noted that it just feels "un-java-like", which I am one to agree with. Java's verbosity can be both a blessing and a curse, but it does make the language what it is.

Of course that particular RFE was not the end of that conversation. During Java 7, this feature was again considered, with some test implementations being created, including one by James Gosling himself. Again, this feature was ultimately shot down.

With the release of Java 8, we now get type inference as a part of lambdas as such:

List<String> names = Arrays.asList("Tom", "Dick", "Harry");
Collections.sort(names, (first, second) -> first.compareTo(second));

The Java compiler is able to look at the method Collections#sort(List<T>, Comparator<? super T>) and then the interface of Comparator#compare(T o1, T o2) and determine that first and second should be a String thus allowing the programmer to forgo having to restate the type in the lambda expression.


答: I can think of a few possible reasons. One is that explicit typing is self-documenting. Java generally makes this a priority over concision. Another reason might be in cases where the type is somewhat ambiguous. Like when a type or any subtype might satisfy a routine. Let's say you want to use a List, but someone comes along and uses a method exclusive to ArrayList. The JIT would infer an ArrayList and carry on even if you wanted a compilation error.</p>

ContentLicense: CC BY-SA 3.0

Title: Why does Java not do type inference?

Body: I have always wondered why Java does not do type inference given that the language is what it is, and its VM is very mature. Google's Go is an example of a language with excellent type inference and it reduces the amount of typing one has to do. Is there any special reason behind this feature not being a part of Java?</p>


答:
Well, first off, type inference has nothing to do with the maturity of the runtime, whether that runtime is a 30 year old CPU or a VM that is so new the bits are still shiny.  it's all about the compiler.

That said, it is allowed for generics, the reason why it's not allowed for non-generic types seems to be because of philosophy -- there's nothing preventing the designers from adding it.

Update: looks like java 10 supports it —- http://openjdk.java.net/jeps/286

Title: Why does Java not do type inference?

ContentLicense: CC BY-SA 4.0


问:
Which Common Lisp implementation to use?
There seems to be an immediate problem with starting to develop in Common Lisp: choosing an implementation. What should one take into account, and how much weight should it bear when considering a CL implementation?

Should it conform to the ANSI standard? Should it be supported by SLIME? Do certain implementations lack good libraries, documentation, etc?

答:
It depends on your specific needs, and the strenghts and weaknesses of the particular implementations. That said, here is what first comes to my mind when thinking about different implementations:

SBCL is pretty fast, and good at number crunching. So, if you depend on heavy numerical computation, that might be the right implementation for you. Also, it has decent type inference (for a Lisp implementation).

CLISP is a relatively small, byte-compiling implementation that might be interesting for scripting.

A few years ago, I tried CCL and stuck with it, because I preferred its error messages and stack traces to the ones of other implementations, as well as its relatively low compilation times. For me, ease of interactive use is something of very high priority. If its speed is needed, I might still switch to SBCL for the deployed program. (Never needed to, though.) Also, there is the option of commercial support.

If you want to deploy on the JVM, there's ABCL.

For embedded use, ECL.

Allegro has AllegroGraph, AllegroStore, a simple to use visual GUI builder, and much more, but not everybody likes their licensing terms.

LispWorks, seems to lend itself pretty well for end-user application programming with a nice cross-platform GUI toolkit and licensing terms that might fit small teams and single programmers better than Allegro's. (At least it's what I'd prefer.)

Of course, these are just broad categories and impressions. I'd suggest taking a closer look at SBCL, CCL, and CLISP, since those are IMHO the most used and best supported open source implementations, then choosing one of those. That is, unless your needs match with what ABCL or ECL have to offer.

Should it conform to the ASNI standard?

It wouldn't be a CL implementation, if it didn't. (There might, of course, be a few deviations in practice, but conformance should at least be the goal.)

Should it be supported by SLIME?

Sure – if you use SLIME. (In my opinion, it's the best Lisp environment available at the moment, but to each his own.)

Do certain implementations lack good libraries, documentation, etc?

At least SBCL, CCL, Allegro, and LispWorks should be well supported by most of the libraries commonly used. CLISP comes with a pretty nice library collection itself, and should also be supported mostly.


答:
Dan Weinreb (unfortunately he passed away last year) wrote an overview:

Lisp Survey

There are many differences between the CL implementations. It is not possible to cover all different needs (speed, size, license, price, compatibility, operating system support, ...) of users for a Lisp system in one implementation. One has to find a local optimum by using one or more of the available implementations, which follow a certain philosophy:

free, no-cost, C-based (thus widely ported): ECL, CLISP

free, no-cost, JVM-based: ABCL

free, no-cost, extensive native implementation: SBCL, CCL, CMUCL

proprietary, commercial, very extensive native implementation, excellent support for GUI-based apps: Allegro CL, LispWorks

by OS/Platform:

JVM: ABCL

Linux: all

Linux with GUI+IDE: Allegro CL, LispWorks

Mac OS X with GUI+IDE: CCL or LispWorks

MS Windows with GUI+IDE: Allegro CL or LispWorks

Android and iOS application delivery: mocl

Title: Which Common Lisp implementation to use?

Body:
There seems to be an immediate problem with starting to develop in Common Lisp: choosing an implementation. What should one take into account, and how much weight should it bear when considering a CL implementation?

Should it conform to the ANSI standard? Should it be supported by SLIME? Do certain implementations lack good libraries, documentation, etc?


问:
Do I need to understand algorithms and data structures to be called a programmer?
It has been six years since I have been coding. Coding into all kinds of things like ActionScript, JavaScript, Java, PHP, Ajax, XML HTML, ASP, etc. I have used arrays, maps, linked lists, sets, etc and wherever I worked people like me. But whenever I am interviewed it is very likely that people ask me question on hashes, trees, stacks, and queues. Some questions are on juggling some sorting algorithms.  I don't know if I should really know them or should I stop calling myself a programmer. There is something in me which also tells me even if people who are asking all these questions select me, they will never be making me work of these things. Am I really required to know all this?</p>

答:
It depends of the project: I'm a BEng in Computer Engineer and I work as analyst programmer.

I spent a lot of time for to work in design (testing, doc, code design).
But, when I find a bug (or bad performance) or I have to coding a new data structure (because the requirement is very NEW for the application), I must to understand where's the problem in the algoritm and I must to correct him (I did this not very good, so :))

The classical algorithms and data structures are a kind of "dictionary pattern" in the world of developer.

Some excellent links:

http://www.joelonsoftware.com/articles/ThePerilsofJavaSchools.html

http://www.joelonsoftware.com/articles/fog0000000319.html

ContentLicense: CC BY-SA 2.5


问:
Frustration with Java Swing layout managers
I have been trying for years to master Swing layout managers with no success.  Every time I need to do something with Swing, it is like pulling nails to get the visual components to line up the way I want them to.  I am familiar with frameworks like Matisse but that's not the point.

My question is:  Why does Swing even need layout managers?  It seems like an overcomlicated paradigm.  What I would like to be able to do is jave a simple JFrame and then for each component (like JLabel) simply specify X and Y coordinates where I want it to be situated -- done deal.  Can anybody explain what is wrong with this simple approach that would work predictably 100% of times?  Or is there an actual layout manager that does things exactly like this?

答:
As already mentioned layoutManagers because screens come in a lot of different sizes.

As already mentioned I would suggest using TableLayout

Most of my screens are fairly simple, I have my own front-end to Swing that allows me to define simple screens like:

```<code>pnl.addLine("Record Name", sfRecordName);
pnl.addLine("Description", sfDescription)
       .setHeight(DESCRIPTION_HEIGHT);
pnl.addLine("Record Type", sfRecordType);
pnl.addLine("System",      sfSystem)
       .setGap(BasePanel.GAP0);
pnl.addLine("List",        sfList);
</code>```

Behind the scene the addLine method uses tableLayout to layout the screen, it also will

optionally set the name of the field (to the prompt) which is useful in some Swing Testing tools (e.g. early versions of Marathon)

Do language conversion

Have a look around, there are various Swing front-end available

Body:
As already mentioned layoutManagers because screens come in a lot of different sizes.

As already mentioned I would suggest using TableLayout

Most of my screens are fairly simple, I have my own front-end to Swing that allows me to define simple screens like:

pnl.addLine("Record Name", sfRecordName);
pnl.addLine("Description", sfDescription)
       .setHeight(DESCRIPTION_HEIGHT);
pnl.addLine("Record Type", sfRecordType);
pnl.addLine("System",      sfSystem)
       .setGap(BasePanel.GAP0);
pnl.addLine("List",        sfList);

Behind the scene the addLine method uses tableLayout to layout the screen, it also will

optionally set the name of the field (to the prompt) which is useful in some Swing Testing tools (e.g. early versions of Marathon)

Do language conversion

Have a look around, there are various Swing front-end available


答:
As far as I know, when Java was designed at the beginning of the nineties type inference was not that popular among mainstream languages (but it was already a very well known concept, e.g. in ML). So, I can imagine that type inference was probably not supported because Java was aimed at programmers coming from C++, Pascal, or other mainstream languages that did not have it (principle of least surprise).

Also, one of the design principles of Java is to write things explicitly to make sure that the programmer and the compiler have the same understanding of the code: duplicating information reduces the chances of errors. Of course, it may be a matter of taste whether typing a few more characters is worth the extra safety it provides, but this was the design philosophy followed for Java: write things explicitly.

I do not know if Java will get type inference in the future but IMO that would be a big revolution for the language (as Glenn Nelson mentioned, it was described as "un-java-like") and then one might also consider dropping the name Java in favour of a new name.

If you want to use a JVM language with type inference you can use Scala.

Title: Why does Java not do type inference?


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答:
The bug is in your code, not the compiler or the runtime libraries.

If you see a bug that cannot possibly happen, check that you have correctly built and deployed your program.  (Especially if you are using a complicated IDE or build framework that tries to hide the messy details from you ... or if your build involves lots of manual steps.)

Concurrent / multi-threaded programs are hard to write and harder to properly test.  It is best to delegate as much as you can to concurrency libraries and frameworks.

Writing the documentation is part of your job as a programmer.  Don't leave it for "someone else" to do.

EDIT

Yes, my point #1 is overstated.  Even the best engineered application platforms do have their share of bugs, and some of the less well engineered ones are rife with them.  But even so, you should always suspect your code first, and only start blaming compiler / library bugs when you have clear evidence that your code is not at fault.

Back in the days when I did C / C++ development, I remember cases where supposed optimizer "bugs" turned out to be a due to me / some other programmer having done things that the language spec says have undefined results.  This applies even for supposedly safe languages like Java; e.g. take a long hard look at the Java memory model (JLS chapter 17).


问:
Brain picking during job interview
Recently, I had a job interview at a big Silicon Valley company for a senior software developer/R&D position. I had several technical phone screens, an all day on-site interview and more technical phone screens for another position later.

The interviews went really well, I have a PhD and working experience in the area I was applying for yet no offer was made. So far, so good. It was an interesting experience, I am employed, absolutely no hard feelings about this.

Some of the interviewers asked really detailed questions to the point of being suspicious about new technologies I have been working on. These technologies are still in development and have not come to market yet. I know some major hardware/software companies are working on this too. I have had many interviews before and based on my former interviewing experience and the impression some of the interviewers left behind, I know now all this company wanted from me is to extract some ideas about what I did in this field. Remember, I am referring to a R&D position, not the standard software developer stuff.

Has anybody encountered this situation so far? And how did you deal with it? I am not so much concerned about "stealing" ideas but more about being tricked into showing up for an interview when there is no intension to hire anyway. I am considering refusing technical interviews in the future and instead proposing a trial period in which the company can easily reconsider its hiring decision.

答:
first, vet the interviewer - are they in a competing field? why are they interested in you?

second, refuse to answer any question that goes beyond the general/common knowledge of the field, on non-disclosure-agreement grounds (politely)

third, expect some level of giving them 'free advice'; but cut it off after (say) 3-5 minutes.

fourth, take control of the interview as soon as you can, to make sure that your questions get answered. Since you are interviewing from a position of strength it is important that you understand how you might fit in the company culture, what would be expected of you, where they are at currently with their R&D efforts, and so on. You're interviewing them as much if not more than they are interviewing you.

good luck!

Title: Brain picking during job interview


问:
Declaring Clean Data
```<code>$clean = array();

$email_pattern = '/^[^@\s<&>]+@([-a-z0-9]+\.)+[a-z]{2,}$/i';

if (preg_match($email_pattern, $_POST['email']))
{
$clean['email'] = $_POST['email'];
}
</code>```

The example code above (Source) uses an array called $clean to store the filtered value from $_POST. It's considered a security good practice. What are the advantages of using such an approach?

答:
Using this approach compared to which one? Not validating the input? Validating the input but storing it back in $_POST?

Not validating the input at all is harmful security-wise, since it means that you fully trust any user. Note that client-side validation doesn't count, since circumventing it is elementary.

By the way, here, validation is incomplete and especially encourage DOS attacks. If a malicious person submits a very large value for the field, evaluating it with the regular expression will take a huge amount of time and resources, eventually resulting in a denial of service if the request is repeated enough times.

In the particular case of the e-mail address, the validation is also incorrect. But it's up to you to decide whether you are ready to use the real, RFC822-compliant, regular expression instead or stick with an incorrect one.

Storing values back to $_POST, i.e. doing something like:

```<code>if (!AppController::ValidateEmail($_POST['email']))
{
    unset($_POST['email']);
}
</code>```

is less risky, since $_POST values wouldn't be reassigned by the user, but still has a drawback: you're using a variable which is in global scope. This means that if you are calling some code between the moment when you validate the inputs and when you use them, this intermediary code can modify the $_POST data and introduce unexpected values.

Title: Declaring Clean Data

Body:
Using this approach compared to which one? Not validating the input? Validating the input but storing it back in $_POST?

Not validating the input at all is harmful security-wise, since it means that you fully trust any user. Note that client-side validation doesn't count, since circumventing it is elementary.

By the way, here, validation is incomplete and especially encourage DOS attacks. If a malicious person submits a very large value for the field, evaluating it with the regular expression will take a huge amount of time and resources, eventually resulting in a denial of service if the request is repeated enough times.

In the particular case of the e-mail address, the validation is also incorrect. But it's up to you to decide whether you are ready to use the real, RFC822-compliant, regular expression instead or stick with an incorrect one.

Storing values back to $_POST, i.e. doing something like:

if (!AppController::ValidateEmail($_POST['email']))
{
    unset($_POST['email']);
}

is less risky, since $_POST values wouldn't be reassigned by the user, but still has a drawback: you're using a variable which is in global scope. This means that if you are calling some code between the moment when you validate the inputs and when you use them, this intermediary code can modify the $_POST data and introduce unexpected values.


答:
What I would like to be able to do is jave a simple JFrame and then
  for each component (like JLabel) simply specify X and Y coordinates
  where I want it to be situated -- done deal.

You can do that with null layout:

```<code>jPanel.setLayout(null);
jLabel.setBounds(5, 5, 200, 300);
jPanel.add(jLabel);
jFrame.add(jPanel);
</code>```

Title: Frustration with Java Swing layout managers

Body:
I have been trying for years to master Swing layout managers with no success.  Every time I need to do something with Swing, it is like pulling nails to get the visual components to line up the way I want them to.  I am familiar with frameworks like Matisse but that's not the point.

My question is:  Why does Swing even need layout managers?  It seems like an overcomlicated paradigm.  What I would like to be able to do is jave a simple JFrame and then for each component (like JLabel) simply specify X and Y coordinates where I want it to be situated -- done deal.  Can anybody explain what is wrong with this simple approach that would work predictably 100% of times?  Or is there an actual layout manager that does things exactly like this?

Body:
What I would like to be able to do is jave a simple JFrame and then
  for each component (like JLabel) simply specify X and Y coordinates
  where I want it to be situated -- done deal.

You can do that with null layout:

jPanel.setLayout(null);
jLabel.setBounds(5, 5, 200, 300);
jPanel.add(jLabel);
jFrame.add(jPanel);


问:
How to program object-oriented with a DI framework?

Possible Duplicate:

  Does “Inversion of Control” promote “Anemic Domain Model”?

My impression is that projects using a DI framework like Spring or Guice tend to lose their object orientation and degenerate to a purely procedural design:

DI not only centralizes the question of which implementation of an object to use but also manages the life-cycle of these objects. Many OO design patterns, however, rely on the ability of business logic to wire objects. I wouldn't know, for example, how to implement a Strategy Pattern in Spring because the decision which of the concrete strategies to use, is statically determined by the configuration of the application instead of a piece of code. Same goes for decorator, composite, observer, ...

The reason above leads to a design where functionality and data are separated. Because you don't want to let the DI container decide when data is created, you split any code off the data in order to have only this part managed by the DI container. This is contrary to the idea of OO where code and data should reside together in one unit. This breaks the encapsulation of data because all fields of the data "beans" are exposed by public getters and setters.

You can't use polymorphism anymore because code is not linked to its data anymore and the "virtual functions" can't work. This leads to those instanceof cascades that we all know we shouldn't use. Also, we lose all those designs that rely on polymorphism.

The DI container will inject managed beans only in objects which are also managed by it. So you can't mix managed beans and normal objects because there can't be any "non-managed gaps" in the reference chain of managed beans. So once you started with DI, you need to put all other code under the control of the DI container and you can't use normal objects anymore. I suppose that this is the reason why the separation of code and data is done so rigorously in DI projects.

I see that there are reasons why to use DI but is it really worth giving up so much? Don't people care about OO? Apart from this article, I can't find any discussions on this topic.

Or is it just me who doesn't understand how to do this properly? Any ideas how the four points above can be tackled with?

Appendix 1: Explanation of strategy pattern

I refer to the example here. Let's assume there's a DI version of it where all implementations of Strategy and the Context are injected to StrategyExample. Then StrategyExample doesn't decide anymore which Strategy to inject into Context but the configuration would have already decided which implementation to inject into Context. So yes, DI heavily applies the Strategy Pattern. But it always does so statically.

答:
DI not only centralizes the question of which implementation of an
  object to use but also manages the life-cycle of these objects. Many
  OO design patterns, however, rely on the ability of business logic to
  wire objects. I wouldn't know, for example, how to implement a
  Strategy Pattern in Spring because the decision which of the concrete
  strategies to use, is statically determined by the configuration of
  the application instead of a piece of code. Same goes for decorator,
  composite, observer, ...

That's simply not true. I think strategy is a prime example for one pattern that actually benefits from DI and is by itself (with or without container) the prototype of DI. You can export as many strategies as you like and pick the one that you want in your business logic. Also, no one, I repeat nothing and no one stops you from instantiating a known strategy by yourself to override the strategy that was injected.

The reason above leads to a design where functionality and data are
  separated. Because you don't want to let the DI container decide when
  data is created, you split any code off the data in order to have only
  this part managed by the DI container. This is contrary to the idea of
  OO where code and data should reside together in one unit. This breaks
  the encapsulation of data because all fields of the data "beans" are
  exposed by public getters and setters.

I see your point but you can easily resolve this by using a factory pattern. In the simplest way, you can instantiate your object yourself and then have it built up and wired by the factory (calling and hiding the container's implementation).

You can't use polymorphism anymore because code is not linked to its
  data anymore and the "virtual functions" can't work. This leads to
  those instanceof cascades that we all know we shouldn't use. Also, we
  lose all those designs that rely on polymorphism.

I totally don't see your point here. Dependency Injection done right is a really good example for the power of polymorphism by itself.

The DI container will inject managed beans only in objects which are
  also managed by it. So you can't mix managed beans and normal objects
  because there can't be any "non-managed gaps" in the reference chain
  of managed beans. So once you started with DI, you need to put all
  other code under the control of the DI container and you can't use
  normal objects anymore. I suppose that this is the reason why the
  separation of code and data is done so rigorously in DI projects.

Yes, but this can easily be resolved with a factory approach. You totally can build software that runs with or without a DI container by using a simple factory.


答:
I don't think DI throws OO principles out the window; in may ways, DI is dependent on them.

I'll keep this answer generic, since most DI frameworks borrow very heavily from one another.  The concepts are similar, though some frameworks have features that others don't.  I will assume, however, that the framework accepts external configuration that is read at runtime (like XML or properties file(s)), possibly in addition to compile-time configuration (like attributes).

In a DI world, you become more heavily dependent on interfaces and composition.  For example, say your application needs to get a price of a product, and that price might come from a CSV file, or a database, or a REST service.  You can define the interface as something like

```<code>public interface PricingService {
  public int getPrice(String productId);
}
</code>```

with implementations

```<code>public class FilePricingService implements PricingService {
  public void setParser(Parser parser) { ... } // and getter
  public void setPriceFile(File file) { ... }  // and getter

  private Map<String, Integer> prices;
  public void init() {
    getParser().parse(getPriceFile());
     prices = ...;
  }

  public int getPrice(String productId) {
    return prices.get(productId);
  }
}
</code>```

A decent DI system would be able to introspect the property types of this object, and call the setters with the appropriate objects.  When an object is first referenced, the framework looks up all of the depended-upon objects, and calls the object's init() method if it has one.   For example, a property file based configuration (just to make the example simpler) may look like:

```<code># Application.properties
class=...
pricingService=CSVPricingService

# CSVPricingService.properties
class=FilePricingService
parser=CSVParser # defined elsewhere
priceFile=/path/to/prices.csv

# XMLPricingService.properties
class=FilePricingService
parser=XMLParser # defined elsewhere
priceFile=/path/to/prices.xml
</code>```

So at runtime, the configuration can be changed without having to recompile anything.  The framework knows that the FilePricingService is expecting priceFile t be a File, so it invokes its own converters to automagically create a File from the filename that was provided.  It knows that Parser is not a simple type, so it assumes this is a reference to another DI-managed component, and looks up that component.  This is especially handy if you don't have the source to the components you want to use.  Extending the example:

```<code>public class RESTPricingService implements PricingService {
  public void setEndpointURL(URL endpoint) { ... }

  public int getPrice(String productId) { ... }
}
</code>```

etc. The idea is that wherever something needs a PricingService, it doesn't have to care what the implementation class is.  Say you had a requirement drop on you that says "pick the lowest price from two different CSV files and the REST service".  The only additional code you'd have to write is a composition class that uses these other existing pricing services:

```<code>public class LowestPricingService implements PricingService {
  public void setPricingServices(List<PricingService> services) { ... }

  public int price(String productId) {
    int lowestPrice = Integer.MAX_VALUE;
    for(PricingService s : getPricingServices()) {
      int p = s.getPrice(productId);
      if(p < lowestPrice) {
        lowestPrice = p;
      }
    }
  }
}
</code>```

And you can create a configuration file that looks like

```<code># FileOnePricingService.properties
class=FilePricingService
parser=CSVParser
file=/path/to/file/one.csv

# FileTwoPricingService.properties
class=FilePricingService
parser=CSVParser
file=/path/to/file/two.csv

# RESTPricingService.properties
class=RESTPricingService
endpointURL=https://example.com/price

# FilesAndRESTPricingService.properties
class=LowestPricingService
pricingServices=FileOnePricingService,FileTwoPricingService,RESTPricingService
</code>```

and tell the application to use that FilesAndRESTPricingService in its configuration.

This system is dependent on many OO priciples.  Polymorphism/inheritance, encapsulation, etc., are all in use here.  Java makes some of this a lot more verbose, with boilerplate getters and setters everywhere, but that's a deficiency of the language, not of the DI pattern.  (Imagine a Java with macros that allow you to say { property File theFile; }  which would create the getter/setter code).

The benefit of using a DI system like this is the framework handles a lot of the configuration for you.  A good DI system would also provide a way for you to inspect the runtime configuration of the objects via some UI.  At runtime, if you needed to change the list of PricingServices, for example, the framework UI should be able to show you all of the registered implementations, and let you change their dependencies on the fly.

Systems like this exist, and have existed for over a decade, in real-world production settings.

Title: How to program object-oriented with a DI framework?

Body:
Possible Duplicate:

  Does “Inversion of Control” promote “Anemic Domain Model”?

My impression is that projects using a DI framework like Spring or Guice tend to lose their object orientation and degenerate to a purely procedural design:

DI not only centralizes the question of which implementation of an object to use but also manages the life-cycle of these objects. Many OO design patterns, however, rely on the ability of business logic to wire objects. I wouldn't know, for example, how to implement a Strategy Pattern in Spring because the decision which of the concrete strategies to use, is statically determined by the configuration of the application instead of a piece of code. Same goes for decorator, composite, observer, ...

The reason above leads to a design where functionality and data are separated. Because you don't want to let the DI container decide when data is created, you split any code off the data in order to have only this part managed by the DI container. This is contrary to the idea of OO where code and data should reside together in one unit. This breaks the encapsulation of data because all fields of the data "beans" are exposed by public getters and setters.

You can't use polymorphism anymore because code is not linked to its data anymore and the "virtual functions" can't work. This leads to those instanceof cascades that we all know we shouldn't use. Also, we lose all those designs that rely on polymorphism.

The DI container will inject managed beans only in objects which are also managed by it. So you can't mix managed beans and normal objects because there can't be any "non-managed gaps" in the reference chain of managed beans. So once you started with DI, you need to put all other code under the control of the DI container and you can't use normal objects anymore. I suppose that this is the reason why the separation of code and data is done so rigorously in DI projects.

I see that there are reasons why to use DI but is it really worth giving up so much? Don't people care about OO? Apart from this article, I can't find any discussions on this topic.

Or is it just me who doesn't understand how to do this properly? Any ideas how the four points above can be tackled with?

Appendix 1: Explanation of strategy pattern

I refer to the example here. Let's assume there's a DI version of it where all implementations of Strategy and the Context are injected to StrategyExample. Then StrategyExample doesn't decide anymore which Strategy to inject into Context but the configuration would have already decided which implementation to inject into Context. So yes, DI heavily applies the Strategy Pattern. But it always does so statically.

Body:
I don't think DI throws OO principles out the window; in may ways, DI is dependent on them.

I'll keep this answer generic, since most DI frameworks borrow very heavily from one another.  The concepts are similar, though some frameworks have features that others don't.  I will assume, however, that the framework accepts external configuration that is read at runtime (like XML or properties file(s)), possibly in addition to compile-time configuration (like attributes).

In a DI world, you become more heavily dependent on interfaces and composition.  For example, say your application needs to get a price of a product, and that price might come from a CSV file, or a database, or a REST service.  You can define the interface as something like

public interface PricingService {
  public int getPrice(String productId);
}

with implementations

public class FilePricingService implements PricingService {
  public void setParser(Parser parser) { ... } // and getter
  public void setPriceFile(File file) { ... }  // and getter

  private Map<String, Integer> prices;
  public void init() {
    getParser().parse(getPriceFile());
     prices = ...;
  }

  public int getPrice(String productId) {
    return prices.get(productId);
  }
}

A decent DI system would be able to introspect the property types of this object, and call the setters with the appropriate objects.  When an object is first referenced, the framework looks up all of the depended-upon objects, and calls the object's init() method if it has one.   For example, a property file based configuration (just to make the example simpler) may look like:

# Application.properties
class=...
pricingService=CSVPricingService

# CSVPricingService.properties
class=FilePricingService
parser=CSVParser # defined elsewhere
priceFile=/path/to/prices.csv

# XMLPricingService.properties
class=FilePricingService
parser=XMLParser # defined elsewhere
priceFile=/path/to/prices.xml

So at runtime, the configuration can be changed without having to recompile anything.  The framework knows that the FilePricingService is expecting priceFile t be a File, so it invokes its own converters to automagically create a File from the filename that was provided.  It knows that Parser is not a simple type, so it assumes this is a reference to another DI-managed component, and looks up that component.  This is especially handy if you don't have the source to the components you want to use.  Extending the example:

public class RESTPricingService implements PricingService {
  public void setEndpointURL(URL endpoint) { ... }

  public int getPrice(String productId) { ... }
}

etc. The idea is that wherever something needs a PricingService, it doesn't have to care what the implementation class is.  Say you had a requirement drop on you that says "pick the lowest price from two different CSV files and the REST service".  The only additional code you'd have to write is a composition class that uses these other existing pricing services:

public class LowestPricingService implements PricingService {
  public void setPricingServices(List<PricingService> services) { ... }

  public int price(String productId) {
    int lowestPrice = Integer.MAX_VALUE;
    for(PricingService s : getPricingServices()) {
      int p = s.getPrice(productId);
      if(p < lowestPrice) {
        lowestPrice = p;
      }
    }
  }
}

And you can create a configuration file that looks like

# FileOnePricingService.properties
class=FilePricingService
parser=CSVParser
file=/path/to/file/one.csv

# FileTwoPricingService.properties
class=FilePricingService
parser=CSVParser
file=/path/to/file/two.csv

# RESTPricingService.properties
class=RESTPricingService
endpointURL=https://example.com/price

# FilesAndRESTPricingService.properties
class=LowestPricingService
pricingServices=FileOnePricingService,FileTwoPricingService,RESTPricingService

and tell the application to use that FilesAndRESTPricingService in its configuration.

This system is dependent on many OO priciples.  Polymorphism/inheritance, encapsulation, etc., are all in use here.  Java makes some of this a lot more verbose, with boilerplate getters and setters everywhere, but that's a deficiency of the language, not of the DI pattern.  (Imagine a Java with macros that allow you to say { property File theFile; }  which would create the getter/setter code).

The benefit of using a DI system like this is the framework handles a lot of the configuration for you.  A good DI system would also provide a way for you to inspect the runtime configuration of the objects via some UI.  At runtime, if you needed to change the list of PricingServices, for example, the framework UI should be able to show you all of the registered implementations, and let you change their dependencies on the fly.

Systems like this exist, and have existed for over a decade, in real-world production settings.


问:
Need some input on storing stdin, stdout, stderr information for debugging
I am working with a legacy system that is not too bad, but I thought of making some improvements to it, and I wanted to solicit your feedback to help me make good decisions. The platform is Linix (different flavors of it).

The system revolves around running [sometimes long] "jobs" - command line programs. The jobs usually succeed but sometimes may fail, and when they do it is very important to diagnose what went wrong efficiently, and fix the underlying problems (if any) and restarting a job.

We are not using any third-party software for this because we need full control over the process. Right now information about a job is being saved on disk as files - there is one file for stdin, one file that stores the exit code, one file for stdout and stderr combined, and I also know exactly how the process was started - what was the name of the command and what were the arguments.

Now ... I thought about splitting stdout and stderr outputs into different files, but then realized that when they are combined together, one can see the chronological order of messages, except that it now takes a human judgement to tell which was output and which contains the errors. Taking this to a further extreme - why not throw stdin into the mix? It might matter for debugging purposes what the specific line of input was that caused a failure. Ideally the error message would be descriptive enough to give plenty of context, but this does not always happen.

I am looking for a clean way to organize this data so that automated logic could be used to aid humans with error diagnostics. With many jobs running these failures do happen rather often. An example of something that I might want to query for - what were the last 20 lines of input that preceded the first line in stderr? I suppose the exact time stamp can be useful, but not that critical. Also, since a logging module is being used, often the output lines already contain time stamps, but not always - I did not write every bit of this legacy system. I can make changes to it; I just do not want to rewrite it.

Could you propose a good way to massage these streams (add some sort of metadata perhaps) to organize things cleanly? The requirement is that not much extra computing power or disk / ram space should be utilized. I suspect that my problem is not unique. Thanks in advance.

答:
When I've had to do this, I've always used a single logfile with "source-and-time" stamps.

Although this can be very useful, there is still the problem that STDOUT is normally buffered, whereas STDERR is normally not. This means that in looking at a combined log of tagged output lines, adjacent lines may not have happened anywhere near each other in time. You can un-buffer STDOUT, but this can introduce a Heisenberg effect so that the program succeeds/fails in different ways.

My solution is to make sure that any calls to log STDERR always flush STDIN first. Yes, this still has a bit of a Heisenberg effect, but it normally is not too bad.

Regarding STDIN: you can store them in the same common log file and during a test run just look for the next line tagged STDIN. You can even use this to do regression testing in that log files from 2 runs should be equivalent (ignoring time).


问:
Applying Denotational Semantics to design of Programs
I've read a bit on denotational semantics (DS) and I'm very intrigued about the process of designing computer programs where types and functions have strong and clear mappings to mathematics.

Are there any resources that discuss designing programs based on DS in detail?  I've seen a few superficial treatments of the subject.

I'm conversant in Haskell, Scala, Common Lisp, and a bit of Scheme so any resources that use those languages would be greatly appreciated.

答:
Denotational design (program design rooted in and flowing from denotational semantics) is my primary methodology. A few years ago while writing about FRP, I got much clearer about what I'd been doing. See Push-pull functional reactive programming. For a more explicit description of the paradigm and a variety of examples, see Denotational design with type class morphisms. Once I became conscious of the pattern, I started looking for it everywhere. Where it fails, I know I have an abstraction leak. For an early, informal description, see Luke Palmer's blog post Semantic Design.

I'm always interested in applications of denotational design, so I'd love to hear about your explorations.

OwnerDisplayName: Tim Stewart


问:
Can someone else patent my open-sourced algorithm?
I've written a recursive search algorithm to find the boundaries of a voxel data structure in order to render it more efficiently. I've looked around, and either it's such a simple and obvious technique that nobody's bothered to patent it, or it's novel and nobody's done it this way before.

It's openly "published" on GitHub and protected under the GPL. I'd like to show it to others, to see if it can be improved, however...

I fear that although I've written and published it, someone may attempt to patent the same idea.

Am I safe, protected by the banners of open source software, or must I attempt to protect myself like the big guns and patent trolls do?

It's my belief that software patents are evil, and that in order for the best software to be written, many eyes need to see it. I'm worried this may be a rather naïve viewpoint on how software is written, though, and I'm curious as to what others think.

答:
It's not as simple as people are making it out to be.

They would have a hard time patenting your code/ algorithm (even though technically these are not patentable, in fact, abstract methods are patented all the time through the device of using a certain phraseology which is little more than a canned incantation involving the words "in one embodiment...")

What they  could and will do, which is just as destructive and limiting to you and your future freedoms, is patent every *single* obvious *continuation* of the stream of thought or idea you were developing.

So on day 1 you release your code and on day 2 they are busy patenting the most obvious applications of your code as a process patent and every single natural extension of your code - what would have been version 1.2 to you. So you still have your code, but it's been relegated to a progress-ghetto that it can't get out of.

If you think about it, this is all they do already. They don't own the basis of any technology per se (although it took numerous court decisions and hundreds of millions of tax payer dollars to tell them this) . What they do lay claim to and what American courts uphold on a regular basis is just the further extension or natural elaboration or application of other people's ideas.

There is nothing stopping them from including in this what would have otherwise been the natural course of development of your code.

There is no way to improve the quality of software patents because once you've permitted the patenting of ideas- which is all software patents are- there exists no natural line such patents can't cross with enough lawyering  and weasel words.

The dog and pony show the USPTO is putting on now is just because the general public is aware that software patents are insane, thanks mostly to NPR's show about patent trolls and the insane patent wars between Apple and Samsung over smartphones and rounded rectangles and every other twit and twiddle of an idea.

The only result that is ever going to keep you free to code and create in the US without fearing the day you get served and sued for damages is  complete ban on all software patents. Since lawyers run the US to a greater degree than any other country on earth and the USPTO's  bread and water is the fees people pay to patent things, there is no motivation on the part of anyone in power to just shut up and ban software patents.

All this is relevant to your question. No, you cannot meaningfully reach a safe harbor for code, non-trivially defined to include your future releases, away from litigation and software patents. Yes, it would be hard to patent the exact thing you opened source, but that doesn't actually do you that much good. No, this is not going to change in the near future in the US because banning software patents is not even on the table.

Your best solution is to not release code into countries that permit and have a history of enforcing software patents. I also suggest you fight like heck against the forces that seek to extend software patents into countries that currently ban them.

You can make a good living selling into those countries which permit software to be written without fear of lawyer-based terrorism. Releasing software into the US is just asking for trouble until and unless the laws which permit software patents change.

Sorry if this sounds harsh, but you're better off knowing the truth and acting upon it than being guided by a hopeful delusion and then having a rude awakening one fine day.

I hope you and everyone reading this realize I am actually being a good friend by speaking frankly and without prejudice or distortion on this topic.


问:
Learning a new language and framework, should I spike a project, or first ground myself in the language fundamentals?
I've got substantial J2EE experience, have worked with Grails, and am comfortable with several languages (Perl, PHP, Smalltalk). I've decided to try a new project using Ruby on Rails. For those who've decided to migrate to a new technology stack, how do you make the transition? Do you learn the details of Ruby first (I've done a few tutorials, and feel like I've got a decent enough grasp of the language to start doing some basic work) or do you do a full Ruby on Rails tutorial, and expand your knowledge from there. I'm leaning towards the latter approach because I feel like I can delve into details of the language as I encounter them. For those who work in Ruby on Rails, how did you learn, and which resources do you recommend?</p>

答: I learned Rails by going through the Agile Web Development with Rails book and immediately applied everything that I learned to a real web project. I ended up with a rather substantial application (mykidslibrary.com) and a deep understanding of the framework.</p>


问:
Is there something like a polymorphic Singleton?
I have a resource loader object that loads objects from the disk or from a ZIP archive, depending on the platform.

It has state (e.g. the path to the directory or the ZIP archive, and possibly some caching in the future), so it needs to be a single instance.

So normally, a Singleton would do. But my problem is that this resource loader has multiple implementations, of which one is chosen at initialisation. So turning the resource loader into a Singleton won't do.

All I can think of is to have a Singleton that holds a reference to the single resource loader. But isn't there a nicer pattern for this?

答:
This have nothing to do with Singleton pattern.

What you need is some kind of resource manager type that would register factories objects, one for each resource type you want it to be able to provide. Each factory object would know how to load the associated resource type.

Then when you want a resource, you use a function to get the resource from a resource manager instance, that will find the the resource already loaded for you or will request the resource-type-specific factory it owns to load it.

It's interface would look like this (but it really depends on your context in the end):

```<code>class ResourceManager
{
public:

    template<ResourceType>
    void add_factory( std::shared_ptr<ResourceFactory<ResourceType>> factory );

    template<Resourcetype>
    std::shared_ptr<ResourceType> get(); // will look into registered factories and provide a resource instance if it

};
</code>```

This is classical way to manage resources gathered in an object.

Once you have such type (a ResourceManager class for example) working, it's easy to make it (or not, as others will suggest) Singleton. I don't recommend it though.

It's not your class that is polymorphic, it's the resource type.

A better way, most of the time, would be to pass a reference to the resource manager instance into functions and types that need it. There are cases where making it a singleton would be better, but it's very rare.

Body:
This have nothing to do with Singleton pattern.

What you need is some kind of resource manager type that would register factories objects, one for each resource type you want it to be able to provide. Each factory object would know how to load the associated resource type.

Then when you want a resource, you use a function to get the resource from a resource manager instance, that will find the the resource already loaded for you or will request the resource-type-specific factory it owns to load it.

It's interface would look like this (but it really depends on your context in the end):

class ResourceManager
{
public:

    template<ResourceType>
    void add_factory( std::shared_ptr<ResourceFactory<ResourceType>> factory );

    template<Resourcetype>
    std::shared_ptr<ResourceType> get(); // will look into registered factories and provide a resource instance if it

};

This is classical way to manage resources gathered in an object.

Once you have such type (a ResourceManager class for example) working, it's easy to make it (or not, as others will suggest) Singleton. I don't recommend it though.

It's not your class that is polymorphic, it's the resource type.

A better way, most of the time, would be to pass a reference to the resource manager instance into functions and types that need it. There are cases where making it a singleton would be better, but it's very rare.


答:
What you want sounds like a good case for the Factory pattern. You would write something like:

```<code>class LoaderFactory {
  public Loader getLoader() {
    if (environment1) return ZipLoader.getInstance();
    else if (environment2) return DiskLoader.getInstance();
    else return SomeOtherLoader.getInstance();
  }
}
</code>```

Each type of Loader class is a singleton, and each should implement the Loader interface. Your LoaderFactory performs the logic that determines which type is appropriate to return.

Title: Is there something like a polymorphic Singleton?

Body:
I have a resource loader object that loads objects from the disk or from a ZIP archive, depending on the platform.

It has state (e.g. the path to the directory or the ZIP archive, and possibly some caching in the future), so it needs to be a single instance.

So normally, a Singleton would do. But my problem is that this resource loader has multiple implementations, of which one is chosen at initialisation. So turning the resource loader into a Singleton won't do.

All I can think of is to have a Singleton that holds a reference to the single resource loader. But isn't there a nicer pattern for this?

Body:
What you want sounds like a good case for the Factory pattern. You would write something like:

class LoaderFactory {
  public Loader getLoader() {
    if (environment1) return ZipLoader.getInstance();
    else if (environment2) return DiskLoader.getInstance();
    else return SomeOtherLoader.getInstance();
  }
}

Each type of Loader class is a singleton, and each should implement the Loader interface. Your LoaderFactory performs the logic that determines which type is appropriate to return.


问:
Is function overloading in general considered Evil?
Recently I found about two new programming languages(Vala and google's GO) which don't support method or function overloading and intend on not supporting them in the future ever! The creators of these languages say that overloading is evil and should not be used!(in system programming?)

I was told that the creators of Go Language even say that <s>classes </s> inheritance are evil as well and Go doesn't support that!

My question is:

Are they really that bad that the new languages are omitting them? Or Is there a specific field of usage for that languages which makes them evil? What could be the disadvantage of using such facilities at all?

答: Classes, method overloading, operator overloading... they are all tools. They are suitable in some circumstances, not in others. Don't try to apply labels like "evil" to such things; instead, strive to understand them so you can decide for yourself whether they are useful or not. </p>


答: The premise of your question is flawed: GOO supports both overloading and classes.</p>

Title: Is function overloading in general considered Evil?

Body:
Recently I found about two new programming languages(Vala and google's GO) which don't support method or function overloading and intend on not supporting them in the future ever! The creators of these languages say that overloading is evil and should not be used!(in system programming?)

I was told that the creators of Go Language even say that <s>classes </s> inheritance are evil as well and Go doesn't support that!

My question is:

Are they really that bad that the new languages are omitting them? Or Is there a specific field of usage for that languages which makes them evil? What could be the disadvantage of using such facilities at all?


问:
Generating Deep Arrays: Shallow to Deep, Deep to Shallow or Bad idea?
I'm working on an array structure that will be used as the data source for a report template in a web app.

The data comes from relatively complex SQL queries that return one or many rows as one dimensional associative arrays. In the case of many, they are turned into two dimensional indexed array.

The data is complex and in some cases there is a lot of it.  To save trips to the database (which are extremely expensive in this scenario) I'm attempting to get all of the basic arrays  (1 and 2 dimension raw database data) and put them, conditionally, into a single, five level deep array.  Organizing the data in PHP seems like a better idea than by using where statements in the SQL.

Array Structure

```<code>    Array of years(
            year => array of types(
                            types => array of information(
                                                total => value,
                                                table => array of data(
                                                                index => db array
                                                                    )
                                                        )
                                )
                )
</code>```

My first question is, is this a bad idea.  Are arrays like this appropriate for this situation?

If this would work, how should I go about populating it?  My initial thought was shallow to deep, but the more I work on this, the more I realize that it'd be very difficult to abstract out the conditionals that determine where each item goes in the array.  So it seems that starting from the most deeply nested data may be the approach I should take.

If this is array abuse, what alternatives exist?

Edit

I went ahead with this approach, learning and changing things as I went.  But I ended up with a similar end array.  What I learned in regards to the shallow to deep conundrum was this.

I went into the process thinking of the outer arrays as the largest of a set of cups, containing multitudes of smaller cups which in turn contained another multitude of smaller cup until the last set which in my mind was water (this being the indexed array of database values).  Arrays are not cups...

The idea fell apart when I started legitimately hand drawing out the array structures and found that the base of these arrays, the water filled tiny cups I had envisioned, represented a heck of a lot more data than those big cups.  This lead me to see these deeply nested arrays as towers, with the indexed data representing a base of sorts, tapering up to the tip, which was the containing array.

From there, I figured out that the best way for me to process the data was to gather the bottom data, plug it into it's next layer and then go up the tower plugging each layer into it's next layer.

I'm not sure if I'm right, but I do feel like I understand arrays more now than I did before.

And I'm definitely still not sure if this is the best solution.

答:
Full-disclosure: I'm coming from more of a JSON background but designing with object literals and arrays is pretty much the same problem.

I would design with the following goals:

Always make a data structure as shallow as possible until you start needlessly duplicating values all over the place (i.e. over-flattening to the point where you're needlessly duplicating entire sets for different keys/indeces). People tend to nest things for nesting's sake alone or because it seems like there's too many items in a set. All that matters is whether everything belongs in a given category. Note: with smaller data sets, sometimes flattening everything for simplicity is a great idea, but this doesn't sound like one of those scenarios.

If the ordering of elements isn't critical and a set has a reliable unique value that's useful as a key, convert it from indexed to associative with that unique value as the key. i.e. Don't loop something and check for the right value if you can just reference directly by name. This can drastically reduce the complexity of your access functionality.

On the flipside prefer indexed when multiple items with no reliable unique value are possible or the order you're going to loop through those items in is important (maybe that 2nd point is less critical in PHP).

Don't conditionally format. That thing with 1D when it's only one item or 2D-indexed when it's many sounds like a recipe for pointless logic to me. Looping over a one-element array half or even 75% of the time is much less crufty/brittle.


问:
Migrating legacy procedural code to MVC without rewriting
I recently started working on a PHP application that was built many years ago before the advent of objects and namespaces in PHP. The code is procedural, does not separate presentation logic from business logic, lacks a front end point (front controller), and has files everywhere with a seemingly random folder heirarchy.
However, it works great for customers and despite the code mess it's actually pretty fast.

I'd like to slowly move the codebase into something more maintainable and organized. I put MVC in this title, but truthfully all I really mean is an organized and maintainable.

Key objectives of this effort are:

Not degrade the customer experience in any sort of way while this overhaul takes place (a rewrite is not an option)

Fully separate views from logic

At least have a "best practice" or method for implementing new application end points (routes)

Have a consistent method or layer for persisting data

Begin encapsulating as much code as possible in objects so that unit testing is feasible at some point in time.

答:
Any change you make to a software project involves reconfiguring (i.e. changing the data that the code uses) or rewriting (i.e. changing the code itself). Migrating from one style (procedural) to another (object oriented) is a significant change that will necessarily entail a lot of rewriting. Object oriented design isn't something that you can bolt on as an afterthought. Adopting a paradigm like model-view-controller means rethinking and redesigning the project.

Donald Rumsfeld famously said:

...you go to war with the army you have, not the army you might want or wish to have at a later time.

It sounds like you need to figure out what army you have (how much can you reasonably change, and what tools and knowledge do you have at your disposal) and what battle you're trying to fight (what do you really need to accomplish?). I really don't think you can get to MVC without a lot of rewriting, but you might well be able to reorganize the code to make it easier to understand and maintain.


问:
Need interpretation of section in C# specification
I am reading the C# specification.  I could use clarification on a segment:

C# has a unified type system. All C# types, including primitive types
  such as int and double, inherit from a single root object type. Thus,
  all types share a set of common operations, and values of any type can
  be stored, transported, and operated upon in a consistent manner.
  Furthermore, C# supports both user-defined reference types and value
  types, allowing dynamic allocation of objects as well as in-line
  storage of lightweight structures.

What does “in-line storage of lightweight structures” mean in this context?

答:
Svick's answer is good but I thought I would add a few extra points.

First off, the paragraph is flawed. Pointer types do not inherit from object. Values that are at compile time known to be interface types or type parameter types will, at runtime, be either invalid references or bona-fide instances of something that inherits from object, but it has always struct me as odd to say that these types "inherit" from object; inheritance is the property that members of the ancestor are members of the descendent, but you don't normally think of "ToString" as being a member of IEnumerable. You think of it as being a member of the thing that implements IEnumerable.

The paragraph is also flawed because this is the only place "primitive type" appears in the spec, and it appears without definition. It is therefore both unnecessary and confusing and should be removed.

I've wanted this paragraph to be fixed for a while. Next time I see Mads I'll remind him.

To address your specific question: svick is of course correct but it is helpful to see a specific example. When you say:

```<code>struct ColorfulInt
{
    int value;
    Color color;
    ...
}
</code>```

and you create, say, an array:

```<code>ColorfulInt[] x = new ColorFulInt[100];
</code>```

Then the storage for those 100 ints and 100 Colors goes in the array itself. If ColorfulInt were instead a class then the array would contain 100 references to ColorfulInt, each one of which would have to be individually allocated. Individually allocating those hundred elements is much less efficient in both time and space than simply allocating the storage right in the array itself.

Body:
Svick's answer is good but I thought I would add a few extra points.

First off, the paragraph is flawed. Pointer types do not inherit from object. Values that are at compile time known to be interface types or type parameter types will, at runtime, be either invalid references or bona-fide instances of something that inherits from object, but it has always struct me as odd to say that these types "inherit" from object; inheritance is the property that members of the ancestor are members of the descendent, but you don't normally think of "ToString" as being a member of IEnumerable. You think of it as being a member of the thing that implements IEnumerable.

The paragraph is also flawed because this is the only place "primitive type" appears in the spec, and it appears without definition. It is therefore both unnecessary and confusing and should be removed.

I've wanted this paragraph to be fixed for a while. Next time I see Mads I'll remind him.

To address your specific question: svick is of course correct but it is helpful to see a specific example. When you say:

struct ColorfulInt
{
    int value;
    Color color;
    ...
}

and you create, say, an array:

ColorfulInt[] x = new ColorFulInt[100];

Then the storage for those 100 ints and 100 Colors goes in the array itself. If ColorfulInt were instead a class then the array would contain 100 references to ColorfulInt, each one of which would have to be individually allocated. Individually allocating those hundred elements is much less efficient in both time and space than simply allocating the storage right in the array itself.


答:
There's that saying that if you spend 10,000 hours at a task you'll become an expert.  So I'd say "get coding!"  If you've done the tutorial then write some code to scratch an itch or join an open source ruby on rails project.

If your employer is brave/trusts you - perhaps you can build a small but useful real world project as well.

Title: Learning a new language and framework, should I spike a project, or first ground myself in the language fundamentals?

Body: I've got substantial J2EE experience, have worked with Grails, and am comfortable with several languages (Perl, PHP, Smalltalk). I've decided to try a new project using Ruby on Rails. For those who've decided to migrate to a new technology stack, how do you make the transition? Do you learn the details of Ruby first (I've done a few tutorials, and feel like I've got a decent enough grasp of the language to start doing some basic work) or do you do a full Ruby on Rails tutorial, and expand your knowledge from there. I'm leaning towards the latter approach because I feel like I can delve into details of the language as I encounter them. For those who work in Ruby on Rails, how did you learn, and which resources do you recommend?</p>


答: As far as you describe your project, i do not think it is possible to migrate this, without many, many changes to your existing code-base. You have to re-think every function of your program to convert it into this "new" paradigm (at least for your application)</p>

Title: Migrating legacy procedural code to MVC without rewriting

Body:
I recently started working on a PHP application that was built many years ago before the advent of objects and namespaces in PHP. The code is procedural, does not separate presentation logic from business logic, lacks a front end point (front controller), and has files everywhere with a seemingly random folder heirarchy.
However, it works great for customers and despite the code mess it's actually pretty fast.

I'd like to slowly move the codebase into something more maintainable and organized. I put MVC in this title, but truthfully all I really mean is an organized and maintainable.

Key objectives of this effort are:

Not degrade the customer experience in any sort of way while this overhaul takes place (a rewrite is not an option)

Fully separate views from logic

At least have a "best practice" or method for implementing new application end points (routes)

Have a consistent method or layer for persisting data

Begin encapsulating as much code as possible in objects so that unit testing is feasible at some point in time.


答:
I can see where they're coming from, but as rules I would say these are way too specific for 100% restriction in a language design.

Gigantic 18+ layer convoluted inheritance schemes are pretty well-established as an anti-pattern for instance but inheriting 1-3 levels deep can be perfectly reasonable for solving certain problems depending on what other things a language design allows.

Likewise, it's fairly easy to see how method overloading could be done to excess, making an API so overwrought that you'd have to check the docs every time just to figure out how to use a method for the one of 16 ways you actually need it to work. Whereas, used responsibly, it's fairly easy to see how overloading for similar types in the same pattern could be completely reasonable and not at all difficult to remember. That, even more so than the inheritance thing strikes me as an odd feature to restrict wholesale. But, full-disclosure: I'm comfortable with a paradigm where everything is mutable, you don't have to declare a method twice to overload its arguments, and first class functions rain down from all over the place like candy from a busted-open pinata.

That said, just because I don't like it, doesn't mean languages can't make a good case for being highly restrictive. Java for instance (as I understand it) is essentially a design response to the issue of C/C++ code tending to allow so much granular control that it can be very hard for two devs to understand each other's code. Java's inherent conservatism/protectionism allows a lot more developers to work together on the same project while having less trouble understanding what the other devs are on about because, for instance, everything absolutely must be in a class.  And you don't get things like pointers which are certainly powerful but can also very easily turn a code-base into a waking nightmare in mediocre hands. I might argue that most of the time having a lot of developers in the first place is its own problem but I wouldn't go so far as to say this is never a necessity or that they'd always be better off with the dynamic flexibility of JavaScript or the full-on close-to-chrome granular control of C++.

I would however argue that a general purpose language should probably be more flexible than Java is but that's not something 75% of Stack is likely to agree with me on necessarily.

Languages are inherently about design trade-offs. What this really comes down to is how sold you are on the philosophy in terms of solving the problems you typically need to solve. In this case, I think they're being silly for the vast majority of problems I've personally needed to solve but most of that is web UI stuff.


问:
Implementing Command Pattern in Web Application
I'm looking to implement the command pattern in a web application (asp.net c#)... Since the commands come in text format from the client, what is the best way to translate the string to a command object? Should I use reflection? Currently I just assume the command that comes in matches the file name of a user control. This is a bit of a hack.

Rather than have a select case statement that says if string = "Dashboard" then call Dashboard.Execute(), is there a pattern for working with commands that originate as strings?

答:
This is a command pattern written for django 1.4

It can be used the following way:

```<code>    p = DesignPattern()
    imps = Implementation.objects.filter(project='Example')
    DesignPatterImplementationsM2MBind(p, imps)
</code>```

Django application models.py file:

```<code>    class AbstractM2MBindCommand(AbstractCommand):
        """
        Realizes behaviour design pattern `Command'
        """
        model = None
        model_m2m_field = None

        MAX_COMMA_SEPARATED_LENGTH = 1024

        bound_objects = models.CommaSeparatedIntegerField(max_length=MAX_COMMA_SEPARATED_LENGTH, null=True, blank=True, default=None)
        bound_objects_long = models.TextField(null=True, blank=True, default=None)

        class Meta:
            abstract = True

        @classmethod
        def do(cls, model_instance, queryset_to_link):
            #assert isinstance(queryset_to_link, QuerySet)
            setattr(model_instance, cls.model_m2m_field, queryset_to_link)

            ids =  [u'%d' % item.pk for item in queryset_to_link]

            model_instance.save()

            fk_field = camel_to_underscore_convert(cls.model.__name__)

            cmd = cls()
            cmd.direction = cls.FORWARD
            joined_ids = u','.join(ids)
            if len(joined_ids) > cls.MAX_COMMA_SEPARATED_LENGTH:
                cmd.bound_objects_long = joined_ids
                cmd.bound_objects = None
            else:
                cmd.bound_objects_long = None
                cmd.bound_objects = u','.join(ids)
            setattr(cmd, fk_field, model_instance)
            cmd.save()

        @classmethod
        def undo(cls, command_id):
            pass

         @classmethod
         def redo(cls, command_id):
             pass

    class DesignPatterImplementationsBindCommand(AbstractM2MBindCommand):
        model = DesignPattern
        model_m2m_field = 'implementations'

        design_pattern = models.ForeignKey(DesignPattern)
</code>```

Body:
This is a command pattern written for django 1.4

It can be used the following way:

    p = DesignPattern()
    imps = Implementation.objects.filter(project='Example')
    DesignPatterImplementationsM2MBind(p, imps)

Django application models.py file:

    class AbstractM2MBindCommand(AbstractCommand):
        """
        Realizes behaviour design pattern `Command'
        """
        model = None
        model_m2m_field = None

        MAX_COMMA_SEPARATED_LENGTH = 1024

        bound_objects = models.CommaSeparatedIntegerField(max_length=MAX_COMMA_SEPARATED_LENGTH, null=True, blank=True, default=None)
        bound_objects_long = models.TextField(null=True, blank=True, default=None)

        class Meta:
            abstract = True

        @classmethod
        def do(cls, model_instance, queryset_to_link):
            #assert isinstance(queryset_to_link, QuerySet)
            setattr(model_instance, cls.model_m2m_field, queryset_to_link)

            ids =  [u'%d' % item.pk for item in queryset_to_link]

            model_instance.save()

            fk_field = camel_to_underscore_convert(cls.model.__name__)

            cmd = cls()
            cmd.direction = cls.FORWARD
            joined_ids = u','.join(ids)
            if len(joined_ids) > cls.MAX_COMMA_SEPARATED_LENGTH:
                cmd.bound_objects_long = joined_ids
                cmd.bound_objects = None
            else:
                cmd.bound_objects_long = None
                cmd.bound_objects = u','.join(ids)
            setattr(cmd, fk_field, model_instance)
            cmd.save()

        @classmethod
        def undo(cls, command_id):
            pass

         @classmethod
         def redo(cls, command_id):
             pass

    class DesignPatterImplementationsBindCommand(AbstractM2MBindCommand):
        model = DesignPattern
        model_m2m_field = 'implementations'

        design_pattern = models.ForeignKey(DesignPattern)


答: All the answers are well stated. I just want to impress that polymorphism and singleton are what you might call orthogonal concerns. Polymorphism is more of a concept and how we achieve that concept, while Singleton is defining a pattern and taking advantage of the concept of polymorphism for use cases such as the one you bring up.</p>


问:
Why don't languages include implication as a logical operator?
It might be a strange question, but why there is no implication as a logical operator in many languages (Java, C, C++, Python Haskell - although as last one have user defined operators its trivial to add it)? I find logical implication much clearer to write (particularly in asserts or assert-like expressions) then negation with or:</p>

```<code>encrypt(buf, key, mode, iv = null) {
    assert (mode != ECB --> iv != null);
    assert (mode == ECB || iv != null);
    assert (implies(mode != ECB, iv != null)); // User-defined function
}
</code>```

答:
UPDATE: This question was the subject of my blog in November 2015. Thanks for the interesting question!

Visual Basic 6 (and VBScript) had Imp and Eqv operators. No one used them. Both were removed in VB.NET; to my knowledge, no one complained.

I worked on the Visual Basic compiler team (as an intern) for a full year and never once noticed that VB even had those operators. Had I not been the guy writing the VBScript compiler, and therefore had to test their implementations, I probably would not have noticed them. If the guy on the compiler team doesn't know about the feature and doesn't use it, that tells you something about the popularity and usefulness of the feature.

You mentioned C-like languages. I can't speak to C or C++ or Java but I can speak to C#. There is a list of user-suggested features for C# literally longer than your arm. To my knowledge, no user has ever proposed such an operator to the C# team, and I've gone over that list many, many times.

Features that exist and are unused in one language, and are never requested in another are unlikely candidates to make it into modern programming languages. Particularly when there is not enough time and effort and money available in the budget to make features that people do want.


答:
OK, I am gonna make the foolish assumption that that by "without rewriting" you mean "without starting over". Because once your project would qualify as MVC, you will have rewrote a significant portion of it.

I am not gonna lie to you, its gonna be hard. But it is doable.

Literature

The first thing I would suggest you would be to grab a copy of Michael Feather Working with Legacy Code. Its full of great advice on how to handle and work with the kind of code  you describe. You should also grab Martin Fowler Refactoring and Joshua Kerievsky Refactoring to Pattern. Those techniques will very useful for changing your code.

How to work on the problem

Some important point as you work on your code are

Avoid biting more than you can chew

Always keep your code working

To handle the first point, make sure that you always change a little portion of your code at a time. For the second, make sure that you have acceptance test in place that will make sure that you don't break the code as you change it.

The procedure I used myself when reworking old JSP file like your code was the following

Isolate a specific functionality to rewrite

Write a few Acceptance test that check the behavior (Selenium will be a very good tool)

Now the fun part. Create a new empty class and a UnitTest Suite

Read the code, find the simplest part of code you can put in your class

Test the small statement

Put the code of the statement in your class

Replace the statement with a call to your class

Refactor your class to make it readable, not being afraid to create new classes if you see multiple concern emerge. Don't forget to refactor your test too!

Go to 4, and continue until all the code is in your tested classes

Now, as you extract the procedural code in your class, you will start to see pattern emerge. Duplication will become obvious (old code like this tend to be pretty copy and paste). Reengineer your class to reflect your new comprehension of the problem.

One thing you may notice is that as you go, you will start to go quite faster, because the copy pasted code so prevalent in those application will already be in one of your refactored class. Then you will encounter code written by another person and you be slow again. Its normal.

Don't hesitate to stop from time to time and move code around in your refactored class to create a nicer architecture. As you go, you may end up with an MVCish framework. Or you may have sometime that fit your problem in its own way. The nice thing is that you will a nice suite of test to cover you as you do.

Now of course, the problem is that you will want to add feature to the application sooner than later. You can use that. When you need to add something to a part of code, do the refactoring first for that part of code. That way, you will slowly improve the design as you add feature. Its gonna be slower but in the long run you will go faster because the code will be easier to maintain.

I wish you luck!


问:
Comparison with an outsourced dev center
We are part of a software company which was just acquired by a larger one. This company has a large development center in India; we are based in Europe.

We don't yet know what will happen with our projects, maybe they will be outsourced, maybe not but I want to know if we can rival an indian programmer as what salary is concerned.

I know there are a lot of factors involved here, not just the salary issue, but I just want to get an ideea of the difference.

Can someone mention salaries (in euros or dollars) and associated years of experience. I found some info on the web but it is not that recent.

Thanks in advance!

答:
if you try to compete on price, you are doomed. the difference in cost of living alone guarantees this.

worst-case scenario: your projects are outsourced and you are let go

best-case scenario: you have some specialized knowledge/skills so your part of the project cannot be outsourced...but now you have a bulls-eye on your back

typical-case scenario: your knowledge and experience are just valuable enough to keep you around...to manage the outsourced developers.

probable scenario: nothing will change right away, while the bean-counters run the numbers (based on bad assumptions and no input from those involved). then you'll be surprised at work one morning (see scenarios above)

my advice: forget about salary comparisons; start looking for another job, just in case.


问:
Mostly produce output at programming job but don't learn anything
When I started working a programmer, I learned lots at first, on the job.  Although Ive been given more responsibility, which is good in a way, it is mostly in the form of increased workload. I havent had much time or energy left to learn anything much new day to day. Sometimes I have 1 hr of time and energy left at the end of the day to keep up, but I mostly just produce a lot of the same type of code. It does make sense to spend working hrs producing, since it's the reason why a programmer is  trained and hired. However, I am concerned about if Im falling behind as a programmer, by doing what I was hired for, even if not learning much new. Is this standard for most programmers? </p>

答: I suggest you should extend yourself instead of becoming a good programmer. Programmers code to solve problems and reduce other's workload. However, problems and user's request are endless so it is not just programming could solve. Let's see how a great programmer could solve its workload, becomes the best programmer and earns 250,000 a year. So a good project management and social skill could finish the job much better, thats why a project manager earns more than a programmer usually. Then you should have more free time to spend on researching technique and reviewing other's code, which could really improve your knowledge and stay ahead of other programmers.</p>


答:
Have you read 'The Pragmatic Programmer'? It's quite well known and always a refreshing read.

It contains lots of lateral ways of looking at programming as a pursuit and maybe you could incorporate some of the many suggestions and ways of doing things in to your existing flow.

I haven't read it in years but it could even contain the answer to this specifc question.

It'd definitely be worth the time to squeeze in reading this if you haven't already.

Title: Mostly produce output at programming job but don't learn anything

Body: When I started working a programmer, I learned lots at first, on the job.  Although Ive been given more responsibility, which is good in a way, it is mostly in the form of increased workload. I havent had much time or energy left to learn anything much new day to day. Sometimes I have 1 hr of time and energy left at the end of the day to keep up, but I mostly just produce a lot of the same type of code. It does make sense to spend working hrs producing, since it's the reason why a programmer is  trained and hired. However, I am concerned about if Im falling behind as a programmer, by doing what I was hired for, even if not learning much new. Is this standard for most programmers? </p>


问:
Best Traversing Strategy / Logic Help Needed
Background: Here is the scenario, imagine I have a little Robot. I give this robot a Map, and I want him to traverse the map, after doing so, I want the Robot to tell me the shortest possible path on the map. So here is an example of a Map:

Difficulties: The Robot is given the Map in the form of a HashMap. For the above map it will be something like this:

```<code>A > B, E
B > A, C, E
C > B, E
D > E
E > A, B, C, D, F
F > E
</code>```

So node [ A ] has neighbours [ B ] and [ E ] and so on. The Robot can only know the neighbours of the node it is currently at.

So only when at node [ A ] will the Robot know that the neighbours of [ A ] are [ B ] and [ E ]. The Robot has no way of knowing what neighbours [ B ] has unless it is at [ B ], once there, the Robot can call the getNeighbouringNodes() method to find out the neighbours (Returned to Robot as a List).

Current Thinking: At the moment my logic for getting the shortest path from Start to Exit is as follows:

Essentially, it is a breadth first traversal. Once at the start node [ A ], I get the list of neighbouring nodes, then visit first neighbour in the list [ B ].

Once at [ B ] I call the isThisAnExitNode() method to check that [ B ] is an exit node, if yes, write my short path, and exist the map. If no, I go back to node [ A ] and grab the next neighbour of [ A ] which is [ E ].

Do same with [ E ], now if no Exit node was found, I move onto [ B ] to explore its neighbours.

I think you get the idea.

My question is, am I doing it right? Is there a better, more efficient way than my method of traversal?

Any help would be greatly appreciated.

Thank You.

答:
So long as you know your starting node (which in this case you do), you can use Dijkstra's Algorithm to find the shortest path.  Although you didn't specify if there are weights for the paths, it accounts for that as well so long as there are no negative values allowed in the weights.

This uses the assumption that the robot has some form of memory.  It isn't able to see parts of the map that it is not adjacent to, but memorizing the vertices and their weights is a must for any sort of efficient algorithm.


问:
Where to check that a function actually did what I told it to?
Consider this function intended to kill all running instances of a subprocess:

```<code>killAllFoobars()
{
    pids = getRunningFoobars();

    foreach ( pids as p ) {
        killOneFoobar(p);
    }

    return TRUE;
}
</code>```

Where should I check that in fact all Foobars were killed? Should killOneFoobar() check that its Foobar is now killed? Should killAllFoobars() check that there are no more running Foobars before returning TRUE (seems a bit disingenuous to return TRUE without checking). Should the function calling killAllFoobars() check?

Consider that the check is an expensive operation, so should not be done 'just whenever' but rather only when necessary.

答: Do a count on $pids = getRunningFoobars(); after the foreach is finished to see if there are any that remain running.  You can't return a 'true' just assuming.  It may be an expensive check, but the check is needed before you confirm to the user of your function that it did succeed.


问:
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?

答: Statistically a software project starting is a fair sign that it'll fail, as an overwhelming majority of them do...</p>


问:
CLISP Common Lisp license - can it force my code to be released under GPL?
I came across this about CLISP: *"it all-but-forces your code to be released as GPL" here, when looking for a good Common Lisp implementation.

How can a language force a license on your code? Is this just FUD?

I'm asking because I really don't speak "legalese" so maybe there's something I don't understand here...

I get it that the language is GPL and it compiles to a form of bytecode, but can't I have my program with whatever licences I want?

EDITED: CMUCL -> CLISP (had my head in the wrong place when I wrote the question first time, sorry...)

答:
It appears that the FindingLisp statement may be incorrect, or at least oversimplified.  It says "Like I said previously, I really like CLISP, and I use it for developing on Windows, but the license is not suitable for all code since it all-but-forces your code to be released as GPL."  However, the CLISP Summary says, in part: "You may distribute commercial proprietary applications compiled with CLISP, see file COPYRIGHT in the CLISP distribution."

Having gotten that out of the way...

This is a technical issue with Common LISP.  (I don't know whether it is an issue with other flavors of LISP.  I suspect it is.)

There's this interesting quirk about Common LISP (of which CLISP is just one implementation).  It contains a function, EVAL, that can evaluate ANY well-formed LISP expression, and it contains a compiler, and they are both available AT RUN TIME.  Under certain conditions, the Common LISP runtime may be required to compile a brand-new function, created on the fly, as part of running your application.

Because of this, a compiled binary executable (your application) must include a big chunk of the Common LISP implementation, so it can make EVAL and the compiler available to the application.  At that point, you are effectively linking your application with their code, to make your binary, and you will be redistributing THEIR code along with your code, and you are only allowed to redistribute THEIR code under the conditions imposed by THEIR license.

In the case of CLISP, that's the GPL.  If you don't want to GPL your code, use a different (presumably commercial) implementation of Common LISP (Allegro comes to mind), and pay for the runtime licensing.

This is explained in considerable detail in the early chapters of Paul Graham's "On Lisp".


问:
MVC 3 Page design; split pages into Many partials?
I am currently working on an MVC 3 Web app project where I need to display a lot of information on the front page. I am relatively new at web page layout and design so I have hit a wall in terms of how to structure the code behind for this page.

My first thoughts were to split the page up into as many partials as possible so the View Models are smaller and easier to manage. Although I am not sure if this is the correct way of going about it. Or should I try to fit all the needs of the page into one view model that will display all the information I need?

My question: Should I split my pages up into a lot of small partials or just make it one big page?

答:
Well, I think you should split big views into partials, just like it's preferred to split big methods into smaller ones. The big great views tend to become maintainable only by original creator.

Basic rules, analogous to splitting code into methods, should be applied:

don't split too much --  if the view code does not exceed one-two screens  it's perfectly OK (with the exception of extracting reusable parts)

don't mix low level details with high level concepts -- partials placed at the top level in your view should represent the same level
of generality

rely as little as possible on state maintained somehwere else

Also, use Razor's Display/EditorTemplates whenever possible - they are very helpful kind-of partial views. Get familiar with their abilities of rendering (and model-binding) for collections.


答:
Simplified: If you want to distribute an application you have written based on CLISP, then you would need to publish your code under the GPL. That's a consequence of the way how a typical Lisp systems work - it loads code into one big runtime and thus extends/modifies the Lisp system.

There are various Common Lisp implementations published under other licenses.

Clozure CL, for example, is published under the LLGPL, SCBL is Public Domain with parts licensed as BSD, ...

Title: CLISP Common Lisp license - can it force my code to be released under GPL?

Body:
I came across this about CLISP: *"it all-but-forces your code to be released as GPL" here, when looking for a good Common Lisp implementation.

How can a language force a license on your code? Is this just FUD?

I'm asking because I really don't speak "legalese" so maybe there's something I don't understand here...

I get it that the language is GPL and it compiles to a form of bytecode, but can't I have my program with whatever licences I want?

EDITED: CMUCL -> CLISP (had my head in the wrong place when I wrote the question first time, sorry...)


问:
When do you use a class instead of a record when you do not want to use mutable fields?
I'm imagining a situation where you are creating an F# module in a purely functional style.  This means objects do not have mutable fields and are not modified in place. I'm assuming for simplicity that there is no need to use .NET objects or other kinds of objects. There are two possible ways of implementing an object-oriented kind of solution: the first is to use classes and the second to use records which have fields of functional type, to implement methods.

I imagine you'd use classes when you want to use inheritance but that otherwise records would be adequate, if perhaps clumsier to express. Or do you find classes more convenient than records in any case?

答: MSDN recommends that you use value types for immutable types with "single-value" semantics that have a footprint of 16 bytes or less. This should give you some guidelines to decide.</p>