答:
GPLv1 §7 states:

…Each version is given a distinguishing version number.  If the Program
  specifies a version number of the license which applies to it and "any
  later version", you have the option of following the terms and conditions
  either of that version or of any later version published by the Free
  Software Foundation.  If the Program does not specify a version number of
  the license, you may choose any version ever published by the Free Software
  Foundation. [emphasis mine]

As o11c noted, GPLv1 was more permissive than later versions, and there's the chapter and verse that lets you choose.

Title: GPL - No version mentioned

Body:
```<code>This software is allowed to use under GPL or you need to obtain Commercial License
 to use it in non-GPL project.
</code>```

The above is mentioned on an open source project. It does not mention GPLv3 or GPLv2 explicitly. Does that mean I can use it as GPLv2/3 as per my convenience (as we can with LGPL)

I'm an open source newbie, so I just want to clarify this.


问:
Alternative to language purity

Purity

One of the interesting concepts in Haskell is the purity. However, I am wondering what the pragmatic reasons behind this is - let me explain a bit more before you reject my question.

My main point is that we are going to have side-effect no matter how we might encapsulate these in a language. So, even if a programming language like Haskell is pure, we are just "postponing" the side-effects till a later point.

I understand the idea that purity makes reasoning about programs easier (referential transparency and so on). In Haskell, we encapsulate all side-effects in the type system (the IO monad). As such, we cannot have a side-effect without propagating the IO monad down through the types of all functions calling our impure function, so to speak.

As such, I am very keen on the idea of separating pure functions from impure ones in the type system. This seems like a good way to force ourselves to limit such effects.

Still, Haskell is often getting bashed because of its pure nature - people say it isn't practical or pragmatic. Whether this is true or not is another matter, but the fact is that many people reject Haskell for this reason.

An alternative approach? (let us call it "type pollution")

To me, it seems that the main winning point is not purity itself, but the separation of pure and impure code. If encapsulating IO in a monad is too impractical, why don't we try a simpler approach?

What if we instead labelled every return type and argument type in the system as pure or impure. The D language has en explicit "pure" keyword, but I am thinking that we let functions be pure by default and only mark impure functions.

In an ML-like language this could look like this:

```<code>let square x = x * x

let impure getDbData connectionString = ...

let impure getMappedDbData mapping =
    let dbData = getDbData "<some connection info>"
    in map mapping dbData

let main =  // Compiler error, as it is not marked as impure
    let mappedData = getMappedData square
    in ...
</code>```

Further, calling any impure function would "pollute" the calling functions return type, turning it impure. If it wasn't labelled as such, it would give a compile error.

(of course, passing functions as arguments would need to be checked against the expected purity as well, but it should be easy to infer the expected "purity" of arguments)

(the "impure" label could be inferred as well, by I guess it is better to keep this one explicit, for readability)

Pure functions on the other hand, can be passed anywhere, no matter the expected purity. We could give a pure function as input to a function accepting an impure one. So it is not a symmetric relationship - therefore the word "pollution".

All in all, this would explicitly (and statically checked) separate the codebase into a pure and impure part. In many ways, it is close to the functionality of an IO monad (although the asymmetry probably rules out a 1-to-1 mapping between the two), but with an implicit unwrapping done automatically. Most importantly, many programmers would find it more intuitive and pragmatic than an explicit IO monad or something similar.

And unlike the completely impure solutions, this gives a lot more safety to reason about the pure parts (without standing too much in our way, when defining the impure ones). And all in all, it is mostly a statically enforced version of what most functional programmers consider best practice anyway (the separation).

TL;DR;

Has something like the above described approach ever been tried out? If not, is there any reason why not (both technical, practical, theoretic and philosophical reasons are interesting)?

And finally, would such a purity check be easier to accept for people who claim Haskell is impractical?

Disclaimer

I do not personally hold any grudges towards Haskell and the choice of using monads for IO. In fact, I find Haskell to be one of the most elegant languages in use, and maybe the one language I enjoy the most.

Further, it is clear that the above mentioned approach does not offer something that the IO monad does not - the only thing is that it more closely (visually) resembles impure languages like OCaml, F# and so on, which is bound to make it easier to grasp for many people. In fact, taking existing F# code and adding some "impure" labels would be the only visual difference in code.

Hence, this could be an easy step towards purity for languages that do not have the same ecosystem surrounding monads as Haskell has.

答:
You have described an effect system. It’s true that there are other effect systems than monads, but in practice monads give you a lot of expressive power that you would need to reinvent in any practical effect system you might devise.

For example:

I start by tagging my I/O procedures with an io effect.

My pure functions can still throw exceptions, but throwing exceptions isn’t io, so I add an exn effect. Now I need to be able to combine effects.

I want to have non-I/O functions that use mutation internally on a local heap h, and I want the compiler to make sure that my mutable references don’t escape their scope, so I add an st<h> effect. Now I need parameterised effects.

For higher-order functions, I need to write multiple versions for every combination of effects I want to support—for example, map with a pure function versus map with an impure function. Now I need effect polymorphism.

I notice that my user-defined type could be used to model effects (benign failure, nondeterminism) that the language doesn’t have natively. Now I need user-defined effects.

Monads support all of these use cases:

Functions that may return errors can use the Either monad.

Effects can be combined with monad transformers—if I need exceptions and I/O, I can use the EitherT IO monad.

Monads can be parameterised like any other type; the ST h monad lets you do local mutation on STRefs in the scope of a heap h.

Because of the Monad typeclass, I can overload an operation to work on any kind of effect. For example, mapM :: (Monad m) => (a -> m b) -> [a] -> m [b] works in IO, but it also works in Either or ST or any other monad.

All monads are implemented as user-defined types, except for things like IO and ST which must be implemented in the Haskell runtime.

There are of course some significant warts in Haskell’s use of monads for side effects.

For one thing, monad transformers are generally not commutative, so StateT Maybe is different from MaybeT State, and you have to be careful to choose the combination that you actually mean.

The bigger problem is that a function can be polymorphic in which monad is being used, but it cannot be polymorphic in whether a monad is being used. So we get loads of duplicated code: map vs. mapM; zipWith vs. zipWithM, &c.

Now, in answer to your actual question…

Koka from Microsoft Research is a language with an effect system that does not suffer from these problems. For example, the type of Koka’s map function includes a type parameter e for effects:

```<code>map : (xs : list<a>, f : (a) -> e b) -> e list<b>
</code>```

And this parameter can be instantiated to the null effect, making map work for pure and impure functions alike. In addition, the order in which effects are specified is immaterial: <exn,io> is the same as <io,exn>.

It’s also worth mentioning that Java’s checked exception mechanism is an example of an effect system that people have widely accepted, but I don’t feel it adequately answers your question because it’s not general.

ContentLicense: CC BY-SA 3.0

Title: Alternative to language purity

Body:
You have described an effect system. It’s true that there are other effect systems than monads, but in practice monads give you a lot of expressive power that you would need to reinvent in any practical effect system you might devise.

For example:

I start by tagging my I/O procedures with an io effect.

My pure functions can still throw exceptions, but throwing exceptions isn’t io, so I add an exn effect. Now I need to be able to combine effects.

I want to have non-I/O functions that use mutation internally on a local heap h, and I want the compiler to make sure that my mutable references don’t escape their scope, so I add an st<h> effect. Now I need parameterised effects.

For higher-order functions, I need to write multiple versions for every combination of effects I want to support—for example, map with a pure function versus map with an impure function. Now I need effect polymorphism.

I notice that my user-defined type could be used to model effects (benign failure, nondeterminism) that the language doesn’t have natively. Now I need user-defined effects.

Monads support all of these use cases:

Functions that may return errors can use the Either monad.

Effects can be combined with monad transformers—if I need exceptions and I/O, I can use the EitherT IO monad.

Monads can be parameterised like any other type; the ST h monad lets you do local mutation on STRefs in the scope of a heap h.

Because of the Monad typeclass, I can overload an operation to work on any kind of effect. For example, mapM :: (Monad m) => (a -> m b) -> [a] -> m [b] works in IO, but it also works in Either or ST or any other monad.

All monads are implemented as user-defined types, except for things like IO and ST which must be implemented in the Haskell runtime.

There are of course some significant warts in Haskell’s use of monads for side effects.

For one thing, monad transformers are generally not commutative, so StateT Maybe is different from MaybeT State, and you have to be careful to choose the combination that you actually mean.

The bigger problem is that a function can be polymorphic in which monad is being used, but it cannot be polymorphic in whether a monad is being used. So we get loads of duplicated code: map vs. mapM; zipWith vs. zipWithM, &c.

Now, in answer to your actual question…

Koka from Microsoft Research is a language with an effect system that does not suffer from these problems. For example, the type of Koka’s map function includes a type parameter e for effects:

map : (xs : list<a>, f : (a) -> e b) -> e list<b>

And this parameter can be instantiated to the null effect, making map work for pure and impure functions alike. In addition, the order in which effects are specified is immaterial: <exn,io> is the same as <io,exn>.

It’s also worth mentioning that Java’s checked exception mechanism is an example of an effect system that people have widely accepted, but I don’t feel it adequately answers your question because it’s not general.


问:
Who provides hardware resources in private cloud?
I find myself confusing to understand the concept of private cloud. If a company has an offshore data-center, and now if the company wants to move into a private cloud, what does the company has to do?

If I am correct, in order to use the term cloud, there should be virtualization. If there is no virtualization, there is no cloud. So is a private cloud, where you virtualize your existing data center? Or is it simply throwing out your existing hardware and purchasing hardware from a cloud provider, so that now all your resources are on the Internet?

And also how does the private cloud differ from virtual private cloud?

答:
The answer is, if it's your private cloud, then whoever you choose.

Cloud means something like "software and/or data accessible through the Internet and not necessarily situated at any fixed location." The location might be "Singapore" but not "that slice in that rack in that bay of that data centre".

Private cloud means that you largely own and control the software and the data, but not the hardware. You decide what version of the software to run, how the data is organised and stored, and who gets access to the software and data. Obviously there are degrees of this, but you have the ultimate control of your private cloud, but not the hardware it runs on or exactly where it is located.

Virtualisation is not important, except as a possible implementation mechanism.


问:
Do we need to test 32-bit software in 64-bit Windows?
I'm working in a software development team as software developer. I've been working on the same project for three years now. The software is a 32-bit desktop based C# application in .NET 4. Our target platform in Windows 7 (we had to support Windows XP till last year). The software communicates with various custom hardware for which custom drivers are written. The hardware manufacturing and driver software is written by our client. There is different driver for 32-bit and 64-bit Windows of course.

During our system testing phase, we execute all/most test cases in both 32-bit and 64-bit Windows 7. I can't recall if we got any bug in our software that exist in only one flavor of Windows. Having this experience I've started to wonder, do we really need to test 32-bit software on 64-bit Windows?

What's the industry standard?

答:
Nope. Likewise, when the FDA is done testing new medicines on mice and rats, they skip over testing on monkeys and just sell it for human consumption.

< /sarcasm>

Yes, yes yes yes yes. There is nothing but sadness in store for your software if you do not test every platform you possibly can. Things are always different, and the assumptions in the designer/coder's head during the project usually only come passably close to modelling real life. So please, test your software. Please.


问:
Is it possible to programmatically attach custom metadata to phone calls?
I'm trying to determine if it should be possible for a cell phone app to relay custom data along with a phone call. By "should be possible" I mean that I'm not trying to learn how to do it in iOS/Android/whatever, I'm just trying to determine if:

It is permitted by standards: the standards for the metadata that initiates a phone call allow for it to be extended. (I found all kinds of information about high level phone call APIs and CDRs which are kept after a phone call is made, but nothing in the "this is the data header that leaves your phone when you make a call" category).

I can be sure that my custom data will be forwarded intact by the cellular network nodes.

This type of functionality is typically available to apps (from my research: some cellular functionality is implemented by firmware, other functionality has legal issues and its APIs are restricted to privileged users).

In short, what I would ideally like to hear is something along the lines of:
"When you initiate a phone call, the phone generates this header. This part of the header can be used to send custom data, and cellular network nodes won't mess with it. The API for this should be available; for example on iOS/Android/whatever we have xyz()".

答:
If you want a canonical answer, I think you may need to go to the various standards that define the cell phone network, such as ITU-T, 3GPP, UMTS, etc. They're not light reading and some of them are fairly expensive to obtain.

My understanding is that in classic GSM/3G/ISDN/UMTS/etc. call initiation, there is very little metadata beyond the dialed phone number: there might be a call type (voice/data), an extension/subaddress/DID, possibly an indication of what ring pattern to use, things like that. (And of course in POTS there's no metadata at all.) 3GPP TS 24.008 might be a good place to start looking; it contains the formats of the actual radio packets that are sent and received to set up or tear down a voice call.

I'm not familiar with the newer (4G, LTE, etc) interfaces and they might be able to carry more call metadata, but whether metadata sent by one handset will make it across the network to another handset, or whether any phones have APIs to send or receive that data, is another question.


问:
Is a guardfile part of the private developers environment or the public OSS project?
Let us say I have an open source project on github. Now I wish to include tools required to develop the project so others can easily contribute. It is hard for me to tell when these tools should be included in the project for others to use and when they are a personal preference and part of my private development environment.

For example, I understand that a vim config file should not be part of the project as it is part of my editor of choice. I also understand that a Gemfile should be part of the repository as it is required to run the project. I have a problem where these two cross.

What about a Guardfile[1]? This file would automatically compiles/refreshes certain parts of the project if a specific command is called from the command line. Some few developers may have an IDE or substitute which already does this, however most would be happy to have a project-specific and tailored Guardfile.

Would adding such a file be alright or does it cross the line of the developers environment?

[1] https://github.com/guard/guard

答:
It's part of your private environment. Most people want; some random tool like guard is not something I know or care about, nor want to use if for some reason it managed to be installed. I build projects by typing make, not automatically in the background.

However, I disagree that privately useful files should never be part of the repo. Many projects ship a vim file under tools/ or something. For purity, though, you may wish to put them in a separate repository, perhaps a submodule.


问:
Why design a modern language without an exception-handling mechanism?
Many modern languages provide rich exception handling features, but Apple's Swift programming language does not provide an exception handling mechanism.

Steeped in exceptions as I am, I'm having trouble wrapping my mind around what this means. Swift has assertions, and of course return values; but I'm having trouble picturing how my exception-based way of thinking maps to a world without exceptions (and, for that matter, why such a world is desirable). Are there things I can't do in a language like Swift that I could do with exceptions? Do I gain something by losing exceptions?

How for example might I best express something like

```<code>try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()
</code>```

in a language (Swift, for example) that lacks exception handling?

答:
Exceptions can make code more difficult to reason.  While they aren't quite as powerful as gotos, they can cause many of the same problems due to their non-local nature.  For example, let's say you have a piece of imperative code like this:

```<code>cleanMug();
brewCoffee();
pourCoffee();
drinkCoffee();
</code>```

You can't tell at a glance whether any of these procedures can throw an exception.  You have to read the documentation of each of these procedures to figure that out.  (Some languages make this slightly easier by augmenting the type signature with this information.)  The above code will compile just fine regardless of whether any of the procedures throw, making it really easy to forget to handle an exception.

Additionally, even if the intent is to propagate the exception back to the caller, one often needs to add additional code to prevent things from being left in an inconsistent state (e.g. if your coffeemaker breaks, you still need to clean up the mess and return the mug!).  Thus, in many cases code that uses exceptions would look just as complex as as code that didn't because of the extra cleanup required.

Exceptions can be emulated with a sufficiently powerful type system. Many of the languages that avoid exceptions use return values to get the same behavior.  It's similar to how it's done in C, but modern type systems usually make it more elegant and also harder to forget to handle the error condition.  They may also provide syntactic sugar to make things less cumbersome, sometimes almost as clean as it would be with exceptions.

In particular, by embedding error handling into the type system rather than implementing as a separate feature allows "exceptions" to be used for other things that aren't even related to errors.  (It's well known that exception handling are actually a property of monads.)

ContentLicense: CC BY-SA 4.0

Body:
Exceptions can make code more difficult to reason.  While they aren't quite as powerful as gotos, they can cause many of the same problems due to their non-local nature.  For example, let's say you have a piece of imperative code like this:

cleanMug();
brewCoffee();
pourCoffee();
drinkCoffee();

You can't tell at a glance whether any of these procedures can throw an exception.  You have to read the documentation of each of these procedures to figure that out.  (Some languages make this slightly easier by augmenting the type signature with this information.)  The above code will compile just fine regardless of whether any of the procedures throw, making it really easy to forget to handle an exception.

Additionally, even if the intent is to propagate the exception back to the caller, one often needs to add additional code to prevent things from being left in an inconsistent state (e.g. if your coffeemaker breaks, you still need to clean up the mess and return the mug!).  Thus, in many cases code that uses exceptions would look just as complex as as code that didn't because of the extra cleanup required.

Exceptions can be emulated with a sufficiently powerful type system. Many of the languages that avoid exceptions use return values to get the same behavior.  It's similar to how it's done in C, but modern type systems usually make it more elegant and also harder to forget to handle the error condition.  They may also provide syntactic sugar to make things less cumbersome, sometimes almost as clean as it would be with exceptions.

In particular, by embedding error handling into the type system rather than implementing as a separate feature allows "exceptions" to be used for other things that aren't even related to errors.  (It's well known that exception handling are actually a property of monads.)


问:
How to force "program to an interface" without using a java Interface in java 1.6
In java 1.8 they have wonderful new "default interface methods".  In 1.6 how close can we come?  The goal: use code to keep clients from being able to tell that a class is not a java interface.  If we preserve the right to refactor the class name into a Java Interface we don't need to create a Java interface now.  We just provide the class.  Later, refactoring so the class name becomes an interface wont even touch client code.

From Telastyn's answer in Understanding "programming to an interface":

The "Dependency Inversion Principle" says that an object shouldn't control the creation  of its dependencies, it should just advertise what dependency it needs and let the caller provide it. But it doesn't specify whether the dependency should be a concrete type or an interface.

I want to take advantage of this lack of distinction. I also want to interpret the principle "program to an interface" to mean, "I shouldn't be able to tell if any client code is working with a java Interface or a java Class".  So much so, that later someone could swap out the class for a java interface with the same name and no client code would need to be touched.  That may seem overly strict and not exactly what was meant by these design principles (which try to be ignorant of java's particular quirks) but I'd love to pull it off.

Here's why:  Our development environment doesn't use continuous integration.  Releases that force everyone to integrate their code happen once every... well it hasn't happened in all the years I've been working there.  Worse than that, testing is hugely manual for reasons I wont even attempt to justify.  This means: writing a class that will get used by other people is essentially published because changing it will break someones stream or tested code that is closed and closed hard.  This means: no refactoring the signature of anything public on a shared class.  It feels the same as I expect writing an API for a library must feel.

I believe in YAGNI.  I don't want to do a BDUF.  But this situation tempts me to do silly things like put a Java Interface (big I) on every shared class even though, for now, they only have one implementation.  This is against YAGNI, it annoys developers who consider an unneeded interface to be clutter.

What I really want is the freedom to add that Interface, and maybe alternate implementations, later if needed.  I want to be 100% sure I can do this even when I can't even see all the code that might be written against my widely shared class.  I can only be that sure if I use the compiler to FORCE users to program to my interface (little i).

The question: Can you break this protection w/o using reflection from outside the trusted package?  Is the following the right way to achieve this?  In this environment you only get one shot at getting this right.  I want to know if there is anyway to lock me down to the old implementation from outside the trusted package.  All the commented code is "future" code. Except for the errors in main, which should always be errors.

Here we see someone trying their best to lock us down to an implementation:

```<code>package untrusted;

import trusted.AmIAnInterfaceWithDefaultImplementation;
import trusted.WhoKnowsWhatImplementation;

public class Activate {

    public static void main(String[] args) {
        System.out.println( WhoKnowsWhatImplementation.thisProvides().letsFindOut() );

        AmIAnInterfaceWithDefaultImplementation i =
            WhoKnowsWhatImplementation.thisProvides();

        System.out.println( i.letsFindOut() );

        //Error: AmIAnInterfaceWithDefaultImplementation i = new AmIAnInterfaceWithDefaultImplementation();
        //Error: The constructor AmIAnInterfaceWithDefaultImplementation() is not visible
    }
    //Error: public class ImGonnaForceYouToBeAClass extends AmIAnInterfaceWithDefaultImplementation {}
    //Error: The type ImGonnaForceYouToBeAClass cannot subclass the final class AmIAnInterfaceWithDefaultImplementation
}
</code>```

Prints: Default implementation twice.

Here we choose the implementation to provide in a static factory method.  It's only because we're in the same package that the constructor works.

```<code>package trusted;

public class WhoKnowsWhatImplementation {
     public static AmIAnInterfaceWithDefaultImplementation thisProvides() {
        return new AmIAnInterfaceWithDefaultImplementation();
        //return new IAintNoInterfaceNoMore();
    }
}
</code>```

The class below provides both the interface (small i) and the implementation but because the only constructor is protected and the class is final nothing outside the trusted package can force the interface and implementation to stay together.

```<code>package trusted;

/**
 *  Please don't instantiate directly as this may become an Interface.
 *  Use WhoKnowsWhatImplementation
 */
public final class AmIAnInterfaceWithDefaultImplementation {

    protected AmIAnInterfaceWithDefaultImplementation(){}

    public String letsFindOut() {
        return "Default implementation";
    }
}

//public interface AmIAnInterfaceWithDefaultImplementation{
//  public String letsFindOut();
//}
</code>```

We're free to switch to being an interface and push the implementation out to a new class

```<code>package trusted;

//public class IAintNoInterfaceNoMore implements AmIAnInterfaceWithDefaultImplementation {
//
//  @Override
//  public String letsFindOut() {
//      return "Shiny new implementation";
//  }
//}
</code>```

The need for the 'trusted' package comes from a desire not to have the static factory method live on the same class it's instantiating.  It would have to move when we switched to a Java Interface which would impact client code.  That is why the constructor had to be package accessible.

Can you lock this down as a class from outside the trusted package without using reflection?  Is your way of locking it down something that is reasonable to protect against?  What else would you do to protect against getting locked down?  Is there a better approach in java 1.6?

I'd also be interested to know if there is anyway to protect against reflection beyond the java doc begging you not to instantiate it directly but I suspect there isn't.

Many designs fail to adhere to all the design principles. This one violates the open closed principle: classes should be open to extension but closed to modification.  However, this is an attempt to ensure that the classes clients can stay closed even if it changes into a Java Interface.

The example refactoring shown here switches to an interface and implementation class.  It's worth noting that instead it might be decided that the class should actually be abstract.  When we switch to java 1.8, it might even end up as an interface with default methods on it.  The whole point is to preserve the right to make this decision later so we don't have to make it now when we don't know which to do and don't really care.

EDIT: I appreciate all these answers.  Before I accept one, what I'm waiting for is analysis of how vulnerable this approach is to getting locked down to being a class.  I'm willing to accept one that shoots down this whole idea by showing me code that dooms it to forever be a class.  Accepting one that claims it's a sound idea is a nice ego boost but I'd really rather fail here than in the code base.  So convincing me that it's a sound idea is the harder job.

What I've learned from these responses:

Converting from the class to the java interface requires that clients recompile

The class must not expose any more than the java interface could (e.g., no static methods)

Some will insist classes implement Java Interfaces upfront regardless of when they are needed, sigh

The need to recompile the client code strikes me as the most significant issue to be aware of so I'm accepting Maarten Winkels answer.  Thank you all and happy coding.

答:
The correct solution is to use a combination of interfaces and simple factories. This is the general direction you are going, and is the correct way to go. To make this simpler, let's use the analogy of fruit. (The names are a lot shorter.)

We have a Fruit interface, which is in our trusted package:

```<code>package trusted;

public interface Fruit
{
    public void nomnom();
}
</code>```

We have a single implementation of Fruit, Apple. We want the end user to be able to have Apples, but not be able to directly instantiate an Apple:

```<code>package trusted;

final class Apple implements Fruit
{
    @Override
    public void nomnom() {
        System.out.println(nom3() + ", apple!");
    }

    /* Not in Fruit */
    public String nom3() {
        return "Nom, nom, nom";
    }
}
</code>```

Apple is also in the trusted package. First, we note that Apple doesn't have a visibility modifier (public, private, etc.). This means that Apple has the default visibility, which just so happens to be akin to package-private. This means only classes in trusted can access anything about Apple. Outside of trusted, Apple cannot be instantiated (even if it provides a public constructor!), and cannot have any static methods called on it. No one can know anything about Apple. This creates a small problem in that we want clients to be able to get an Apple if they want a Fruit. They cannot directly create one, so we need to provide a FruitFactory with public visibility inside the trusted package:

```<code>package trusted;

public class FruitFactory
{
    /* This could also be an instance method */
    public static Fruit getFruit() {
        return new Apple();
    }
}
</code>```

Now we have a way to get a Fruit (an Apple in this case) without exposing the implementation of Apple. We can see that in action:

```<code>package untrusted;

import trusted.*;

public class Main
{
    public static void main(String[] args) {
        Fruit f = FruitFactory.getFruit();
        f.nomnom();
    }
}
</code>```

And everything works! We can get a Fruit without hassle. If we try to instantiate or access Apple directly in any way from outside trusted, we get a compiler error.

Now say we've come up with the newest and greatest in fruit technology, Orange. Since Apple is now old hat, we're going to give everyone Orange from our factory instead. First, Orange:

```<code>package trusted;

final class Orange implements Fruit
{
    @Override
    public void nomnom() {
        System.out.println("Nom nom nom, orange!");
    }
}
</code>```

And now, all the changes we have to make to get everyone on the Orange bandwagon:

```<code>package trusted;

public class FruitFactory
{
    public static Fruit getFruit() {
        return new Orange();
    }
}
</code>```

Done. Notice that nothing outside of trusted had to change. We didn't touch Main. We didn't even touch Apple. We added Orange, and changed the factory class (the only non-open-closed change, but highly localized and isolated). It still all compiles just fine because we've had them program to the Fruit interface rather than the Apple implementation. All they need to know is to use the FruitFactory to get a Fruit, and don't worry about the rest (the implementation details).

Notice that, because we are now programming to an interface, we don't need to know what the implementation looks like. We should be able to build a client completely by looking only at the Fruit interface, and never at Apple or Orange.

I said that you should definitely use interfaces, and not try to "fake" an interface as a class then try to change it later. There are a number of reasons for this:

If you start with a class, you may end up writing it in such a way that the API is implementation-dependent. Writing an Interface (big-I), without having any implementation in front of you, frees you from thinking about how you are going to do something. Instead you focus on what you want to do.

Writing Interfaces allows you to publish the least amount of information necessary. Interfaces don't carry any implementation, so when you publish it to the rest of your team, all they know is the published API. If you publish an implemented class, it may have a larger API than you intend (note nom3 in Apple, which we'd want to keep hidden), and once others start to depend on those extras, you can never change them, even if you only intended them to be implementation details. A published implementation may also have certain characteristics (performance, etc.) that may not be intrinsic to the API. Others may optimize for that implementation, only to run into trouble when you come out with something new.

By publishing the least amount necessary, you gain freedom. You're always going to need freedom. With a private API, you have the freedom to just make a change, but since all your APIs are essentially published, you need to reserve as much freedom as you can get. Need to swap out an implementation at compile time (like our Apples and Oranges)? No problem. Need to switch out an implementation at runtime? No problem, just have our factory figure out what is needed and give that. Need to implement a feature that requires using another pattern, like decorator or adapter? No problem. Just implement the interface around whatever implementation you need. You don't need to juggle a class-into-an-interface refactoring later, meaning you can be more open-closed as well.

You seem very concerned to make sure that others are technically incapable of using your components in unexpected ways. This accomplishes that, but remember that a determined person will always find a way to circumvent whatever you try to do, even to their own detriment. Document the easy path, show why it is the best. Most people will take the easiest path you provide, and you can sleep soundly.

Body:
The correct solution is to use a combination of interfaces and simple factories. This is the general direction you are going, and is the correct way to go. To make this simpler, let's use the analogy of fruit. (The names are a lot shorter.)

We have a Fruit interface, which is in our trusted package:

package trusted;

public interface Fruit
{
    public void nomnom();
}

We have a single implementation of Fruit, Apple. We want the end user to be able to have Apples, but not be able to directly instantiate an Apple:

package trusted;

final class Apple implements Fruit
{
    @Override
    public void nomnom() {
        System.out.println(nom3() + ", apple!");
    }

    /* Not in Fruit */
    public String nom3() {
        return "Nom, nom, nom";
    }
}

Apple is also in the trusted package. First, we note that Apple doesn't have a visibility modifier (public, private, etc.). This means that Apple has the default visibility, which just so happens to be akin to package-private. This means only classes in trusted can access anything about Apple. Outside of trusted, Apple cannot be instantiated (even if it provides a public constructor!), and cannot have any static methods called on it. No one can know anything about Apple. This creates a small problem in that we want clients to be able to get an Apple if they want a Fruit. They cannot directly create one, so we need to provide a FruitFactory with public visibility inside the trusted package:

package trusted;

public class FruitFactory
{
    /* This could also be an instance method */
    public static Fruit getFruit() {
        return new Apple();
    }
}

Now we have a way to get a Fruit (an Apple in this case) without exposing the implementation of Apple. We can see that in action:

package untrusted;

import trusted.*;

public class Main
{
    public static void main(String[] args) {
        Fruit f = FruitFactory.getFruit();
        f.nomnom();
    }
}

And everything works! We can get a Fruit without hassle. If we try to instantiate or access Apple directly in any way from outside trusted, we get a compiler error.

Now say we've come up with the newest and greatest in fruit technology, Orange. Since Apple is now old hat, we're going to give everyone Orange from our factory instead. First, Orange:

package trusted;

final class Orange implements Fruit
{
    @Override
    public void nomnom() {
        System.out.println("Nom nom nom, orange!");
    }
}

And now, all the changes we have to make to get everyone on the Orange bandwagon:

package trusted;

public class FruitFactory
{
    public static Fruit getFruit() {
        return new Orange();
    }
}

Done. Notice that nothing outside of trusted had to change. We didn't touch Main. We didn't even touch Apple. We added Orange, and changed the factory class (the only non-open-closed change, but highly localized and isolated). It still all compiles just fine because we've had them program to the Fruit interface rather than the Apple implementation. All they need to know is to use the FruitFactory to get a Fruit, and don't worry about the rest (the implementation details).

Notice that, because we are now programming to an interface, we don't need to know what the implementation looks like. We should be able to build a client completely by looking only at the Fruit interface, and never at Apple or Orange.

I said that you should definitely use interfaces, and not try to "fake" an interface as a class then try to change it later. There are a number of reasons for this:

If you start with a class, you may end up writing it in such a way that the API is implementation-dependent. Writing an Interface (big-I), without having any implementation in front of you, frees you from thinking about how you are going to do something. Instead you focus on what you want to do.

Writing Interfaces allows you to publish the least amount of information necessary. Interfaces don't carry any implementation, so when you publish it to the rest of your team, all they know is the published API. If you publish an implemented class, it may have a larger API than you intend (note nom3 in Apple, which we'd want to keep hidden), and once others start to depend on those extras, you can never change them, even if you only intended them to be implementation details. A published implementation may also have certain characteristics (performance, etc.) that may not be intrinsic to the API. Others may optimize for that implementation, only to run into trouble when you come out with something new.

By publishing the least amount necessary, you gain freedom. You're always going to need freedom. With a private API, you have the freedom to just make a change, but since all your APIs are essentially published, you need to reserve as much freedom as you can get. Need to swap out an implementation at compile time (like our Apples and Oranges)? No problem. Need to switch out an implementation at runtime? No problem, just have our factory figure out what is needed and give that. Need to implement a feature that requires using another pattern, like decorator or adapter? No problem. Just implement the interface around whatever implementation you need. You don't need to juggle a class-into-an-interface refactoring later, meaning you can be more open-closed as well.

You seem very concerned to make sure that others are technically incapable of using your components in unexpected ways. This accomplishes that, but remember that a determined person will always find a way to circumvent whatever you try to do, even to their own detriment. Document the easy path, show why it is the best. Most people will take the easiest path you provide, and you can sleep soundly.


答:
One thing I was initially surprised about the Rust language is that it doesn't support catch exceptions. You can throw exceptions, but only the runtime can catch them when a task (think thread, but not always a separate OS thread) dies; if you start a task yourself, then you can ask whether it exited normally or whether it fail!()ed.

As such it is not idiomatic  to fail very often. The few cases where it does happen are, for example, in the test harness (which doesn't know what the user code is like), as the top-level of a compiler (most compilers fork instead), or when invoking a callback on user input.

Instead, the common idiom is to use the Result template to explicitly pass up errors that should be handled. This is made significantly easier by the try! macro, which is can be wrapped around any expression that yields a Result and yields the successful arm if there is one, or otherwise returns early from the function.

```<code>use std::io::IoResult;
use std::io::File;

fn load_file(name: &Path) -> IoResult<String>
{
    let mut file = try!(File::open(name));
    let s = try!(file.read_to_string());
    return Ok(s);
}

fn main()
{
    print!("{}", load_file(&Path::new("/tmp/hello")).unwrap());
}
</code>```

Title: Why design a modern language without an exception-handling mechanism?

Body:
Many modern languages provide rich exception handling features, but Apple's Swift programming language does not provide an exception handling mechanism.

Steeped in exceptions as I am, I'm having trouble wrapping my mind around what this means. Swift has assertions, and of course return values; but I'm having trouble picturing how my exception-based way of thinking maps to a world without exceptions (and, for that matter, why such a world is desirable). Are there things I can't do in a language like Swift that I could do with exceptions? Do I gain something by losing exceptions?

How for example might I best express something like

```<code>try:
    operation_that_can_throw_ioerror()
except IOError:
    handle_the_exception_somehow()
else:
     # we don't want to catch the IOError if it's raised
    another_operation_that_can_throw_ioerror()
finally:
    something_we_always_need_to_do()
</code>```

in a language (Swift, for example) that lacks exception handling?

Body:
One thing I was initially surprised about the Rust language is that it doesn't support catch exceptions. You can throw exceptions, but only the runtime can catch them when a task (think thread, but not always a separate OS thread) dies; if you start a task yourself, then you can ask whether it exited normally or whether it fail!()ed.

As such it is not idiomatic  to fail very often. The few cases where it does happen are, for example, in the test harness (which doesn't know what the user code is like), as the top-level of a compiler (most compilers fork instead), or when invoking a callback on user input.

Instead, the common idiom is to use the Result template to explicitly pass up errors that should be handled. This is made significantly easier by the try! macro, which is can be wrapped around any expression that yields a Result and yields the successful arm if there is one, or otherwise returns early from the function.

use std::io::IoResult;
use std::io::File;

fn load_file(name: &Path) -> IoResult<String>
{
    let mut file = try!(File::open(name));
    let s = try!(file.read_to_string());
    return Ok(s);
}

fn main()
{
    print!("{}", load_file(&Path::new("/tmp/hello")).unwrap());
}


问:
How do I handle a spam server invalidating my tokens?
Our web application sends a one-time use generated token, in the form of an URL, to clients who forget their passwords. This works except for the case where the client is sitting behind another server (i.e. the spam server) that scans their email for URLS and does a GET on the URL. I'm assuming the server is checking for a malicious payload.

The client opens the email and clicks on the link, but obviously nothing happens because the token is invalid at that point.

I can think of some ways of handling this:

• Instead of expiring immediately, allow the token to be valid for a certain time period. Disadvantage: This circumvents the whole point of a one-time use token since the token can be used multiple times. Plus it may not solve the problem if the user decides to open their email PAST the expiration time.

• Make the token good for two uses. Disadvantage: similar to the above. What if the spam checker "checks" the URL again... Sigh.

Anyways, I'm looking for some wisdom here on how to handle this. If there are better ideas than what I've proposed I'd love to hear them.

答:
Those anti-spam servers probably assume that the HTTP GET method is idempotent,which means that each time you use that method on a URL, you get the same result back. Unfortunately for you, this is also how that method is specified in the HTTP standard.

One way to get one-time use tokens to work is to count only when you receive a POST to that URL. This would work like this:

You send the URL with the one-time use token to your client

When they click on the URL (or when some process accesses it with a GET request), you send back a simple page with a form or button to reset or change their password.

When the user presses the button or submits the form, the page sends a POST request to the page's URL (i.e. the one-time use token URL). This would constitute the one use allowed for the token.

After having received the POST, you can either invalidate the URL altogether (all requests get a 404 response) or you can stop responding to POST requests, at your discretion.


问:
Generate all possible outcomes from pattern or range
I have multiple patterns that I want to expand. Expansion should expand number and letter ranges between curly braces. Numbers need to support padding. I want to have it expand into a List(Of String) for ease of iteration. Patterns may include multiple sets of curly braces and they can be in any position.

Here are some example patterns and what they should expand to:

Example 1

```<code>randomtext-aaa-bbb-ccc-{08-10}_abc
    randomtext-aaa-bbb-ccc-08_abc
    randomtext-aaa-bbb-ccc-09_abc
    randomtext-aaa-bbb-ccc-10_abc
</code>```

Example 2

```<code>other_random*text={1-2}
    other_random*text=1
    other_random*text=2
</code>```

Example 3

```<code>{01-02}_more_random-things
    01_more_random-things
    02_more_random-things
</code>```

Example 4

```<code>yet-another#random_example-{a-d}
    yet-another#random_example-a
    yet-another#random_example-b
    yet-another#random_example-c
    yet-another#random_example-d
</code>```

I tried using for loops and sub strings, but it very quickly got confusing and illegible. So how would I go about this without having confusing, illegible code?

答:
So how would I go about this without having confusing, illegible code?

You can either solve the generating problem with recursion or with dynamic data structures that mimic the effect of recursion.

Both are confusing if you don't now the concept yet, but recursion will stop being illegible once you understand it, while the custom data structures will likely remain illegible for good. The obvious recommendation is for you to learn recursion - it is one of the few programming concepts that will almost certainly make you a better programmer, and that will stay with you throughout your career, log after you've solved this one problem.


问:
Why overriding a static method does not result in polymorphism in Java
Many say that we cannot override a static methods.

But we can override a static method.

The question is, when we override a static method why it does not result in polymorphism  ?

答:
Interesting question, I tested it this way:

Superclass

```<code>public class ClassA {
    public static void printStatic(){
        System.out.println("hi static from A");
    }
    public void printDynamic(){
        System.out.println("hi dynamic from A");
    }
}
</code>```

Subclass

```<code>public class ClassB extends ClassA {
    public static void printStatic(){
        System.out.println("hi static from B");
    }
    public void printDynamic(){
        System.out.println("hi dynamic from B");
    }

}
</code>```

Test code

```<code>public static void main (String args[]){
    ClassA x1 = new ClassB();
    x1.printStatic();
    x1.printDynamic();
    ClassB x2 = new ClassB();
    x2.printStatic();
    x2.printDynamic();
}
</code>```

Output

```<code>hi static from A
hi dynamic from B
hi static from B
hi dynamic from B
</code>```

Analysis of test output

Calling a static method allways executes the method in the declaring type, not the overriden  method in the instantiated type (no polymorphism), whereas calling a dynamic method always executes the overridden method in the instantiated type (polymorphism).

My explanation

I think that's because static methods belong to classes, not to objects. That's why eclipse suggest you to call the method in a static way using the name of the class and not the name of the object:

Static methods always refer to the declaration type.

It's the same reason static fields/members/attributes are the same to every object, because they only exist once, in the class itself.

By calling a static method you are specifically telling Java you want the method in the declaring type executed.

I hope my answer doesn't sound like Captain Obvious wrote it.

Body:
Interesting question, I tested it this way:

Superclass

public class ClassA {
    public static void printStatic(){
        System.out.println("hi static from A");
    }
    public void printDynamic(){
        System.out.println("hi dynamic from A");
    }
}

Subclass

public class ClassB extends ClassA {
    public static void printStatic(){
        System.out.println("hi static from B");
    }
    public void printDynamic(){
        System.out.println("hi dynamic from B");
    }

}

Test code

public static void main (String args[]){
    ClassA x1 = new ClassB();
    x1.printStatic();
    x1.printDynamic();
    ClassB x2 = new ClassB();
    x2.printStatic();
    x2.printDynamic();
}

Output

hi static from A
hi dynamic from B
hi static from B
hi dynamic from B

Analysis of test output

Calling a static method allways executes the method in the declaring type, not the overriden  method in the instantiated type (no polymorphism), whereas calling a dynamic method always executes the overridden method in the instantiated type (polymorphism).

My explanation

I think that's because static methods belong to classes, not to objects. That's why eclipse suggest you to call the method in a static way using the name of the class and not the name of the object:

Static methods always refer to the declaration type.

It's the same reason static fields/members/attributes are the same to every object, because they only exist once, in the class itself.

By calling a static method you are specifically telling Java you want the method in the declaring type executed.

I hope my answer doesn't sound like Captain Obvious wrote it.


问:
API to get data, caller may not know how much? How to allocate buffer size
I am writing a C API for retrieving data from a hardware device.  The data will be returned as a string with approximately 30 bytes of text per item.  The problem is there may any number of items.  Could just 10 or there could be 10,000.  So the returned data could range from 10 x 30 = 300 to 10,000 x 30 = 300,000 bytes.

Initially, the function to get the data was like this:

```<code>int get_devicelist(char* devicelist);
</code>```

So the onus is on the caller to know what they are doing and specify a big enough buffer.  Trouble is software using API could be used in many end user applications so the programmer has no end user specific knowledge when they write code to use the API.  The only option then is to specify a buffer (or allocate on heap) that is large enough to hold the largest possible amount of data returned.

So for that reason I am thinking about changing the API as here:

```<code>char* get_devicelist();
void free_devicelist(char* devlist);
</code>```

eg in implementation:

```<code>char* get_devicelist() {
  size_t n = get_devices_size();
  char* devlist = malloc(n * 30);
  if(devlist)
     /* populate devlist */

  return devlist;
}

void free_devicelist(char* devlist) {
   free(devlist);
}
</code>```

Or I just inform users to call free on devlist when no longer needed?

I would change the API code to get the number of devices and then allocate an appropriate amount of memory for devicelist.  The only downside is that the user is then required to call free_devicelist to free the memory allocated.

Is the second API better?  Is there an alternative way?

答:
I'd recommend a look on your OSes APIs how to handle this. For the following example, I refer to the Windows API.

A number of functions with variable buffer outputs follow these rules:

```<code>int GetSomeString( char * pBuf, int nSize);
</code>```

Return value:

If called with pBuf == NULL and nSize == 0, the function returns the required size of the buffer in characters, including the terminating NULL character

If called with pBuf != NULL, the nSize parameter should specifiy the size of *pBuf in characters, including the terminating NULL character. The function will fill the buffer up to nSize chars and return the number of characters written to the buffer

The user is responsible for allocating and freeing the memory.

As a user of the API, I personally find that quite handy. Next, because it is a common pattern, it will be easily understand.

Body:
I'd recommend a look on your OSes APIs how to handle this. For the following example, I refer to the Windows API.

A number of functions with variable buffer outputs follow these rules:

int GetSomeString( char * pBuf, int nSize);

Return value:

If called with pBuf == NULL and nSize == 0, the function returns the required size of the buffer in characters, including the terminating NULL character

If called with pBuf != NULL, the nSize parameter should specifiy the size of *pBuf in characters, including the terminating NULL character. The function will fill the buffer up to nSize chars and return the number of characters written to the buffer

The user is responsible for allocating and freeing the memory.

As a user of the API, I personally find that quite handy. Next, because it is a common pattern, it will be easily understand.


答:
First I take program to an interface to mean more of programming to a contract rather than
programming to a literal Java interface.  Contracts can be implemented in classes or interfaces (or even functions).

I want to take advantage of this lack of distinction. I also want to
  interpret the principle "program to an interface" to mean, "I
  shouldn't be able to tell if any client code (using code) is working
  with a java Interface or a java Class". So much so, that later someone
  could swap out the class for a java interface with the same name and
  no client code would need to be touched. That may seem overly strict
  and not exactly what was meant by these design principles (which try
  to be ignorant of java's particular quirks) but I'd love to pull it
  off.

We run into a similar issue at my workplace.  When everything has an interface, I lose sight of what has multiple implementations and what doesn't.  I might not care about things that do have several implementations when writing code.  But I might care when reading code or debugging code.

There are several potential problems with using classes first and refactoring to an interface.

One of the problems I can see is exposing too many public or package (default) access level methods.  If the client can use public or package protected methods that aren't part of the interface, you can't guarantee that you can safely swap an interface in place for the class.

Theoretically a class is serving the purpose of an interface would if it only exposes methods to the outside that would be present in the interface.  If you can be strict with your classes and only expose methods that would be in the interface, then I fail to see how you couldn't swap them out.

Another problem would be a client using direct construction of the class.
However an interface doesn't prevent me from doing this:

```<code> Foo bar = new DefaultFoo();
</code>```

In order to truly be able to swap instances in and out, you would need Dependency Injection of some flavor.  Also, you may still need to modify client code if you create  multiple implementations.  Something has to know if you wanted a FancyFoo or a PlainFoo for this client.

A final concern would be if the class really implemented more than 1 interface.  You'll find it a lot harder to swap an interface for a class if you have a Frobnicator that implements both the Foo and Bar interfaces.  Clients using Frobnicator might be calling Bar functionality when they only needed a Foo, and vice versa.

Title: How to force "program to an interface" without using a java Interface in java 1.6

Body:
In java 1.8 they have wonderful new "default interface methods".  In 1.6 how close can we come?  The goal: use code to keep clients from being able to tell that a class is not a java interface.  If we preserve the right to refactor the class name into a Java Interface we don't need to create a Java interface now.  We just provide the class.  Later, refactoring so the class name becomes an interface wont even touch client code.

From Telastyn's answer in Understanding "programming to an interface":

The "Dependency Inversion Principle" says that an object shouldn't control the creation  of its dependencies, it should just advertise what dependency it needs and let the caller provide it. But it doesn't specify whether the dependency should be a concrete type or an interface.

I want to take advantage of this lack of distinction. I also want to interpret the principle "program to an interface" to mean, "I shouldn't be able to tell if any client code is working with a java Interface or a java Class".  So much so, that later someone could swap out the class for a java interface with the same name and no client code would need to be touched.  That may seem overly strict and not exactly what was meant by these design principles (which try to be ignorant of java's particular quirks) but I'd love to pull it off.

Here's why:  Our development environment doesn't use continuous integration.  Releases that force everyone to integrate their code happen once every... well it hasn't happened in all the years I've been working there.  Worse than that, testing is hugely manual for reasons I wont even attempt to justify.  This means: writing a class that will get used by other people is essentially published because changing it will break someones stream or tested code that is closed and closed hard.  This means: no refactoring the signature of anything public on a shared class.  It feels the same as I expect writing an API for a library must feel.

I believe in YAGNI.  I don't want to do a BDUF.  But this situation tempts me to do silly things like put a Java Interface (big I) on every shared class even though, for now, they only have one implementation.  This is against YAGNI, it annoys developers who consider an unneeded interface to be clutter.

What I really want is the freedom to add that Interface, and maybe alternate implementations, later if needed.  I want to be 100% sure I can do this even when I can't even see all the code that might be written against my widely shared class.  I can only be that sure if I use the compiler to FORCE users to program to my interface (little i).

The question: Can you break this protection w/o using reflection from outside the trusted package?  Is the following the right way to achieve this?  In this environment you only get one shot at getting this right.  I want to know if there is anyway to lock me down to the old implementation from outside the trusted package.  All the commented code is "future" code. Except for the errors in main, which should always be errors.

Here we see someone trying their best to lock us down to an implementation:

```<code>package untrusted;

import trusted.AmIAnInterfaceWithDefaultImplementation;
import trusted.WhoKnowsWhatImplementation;

public class Activate {

    public static void main(String[] args) {
        System.out.println( WhoKnowsWhatImplementation.thisProvides().letsFindOut() );

        AmIAnInterfaceWithDefaultImplementation i =
            WhoKnowsWhatImplementation.thisProvides();

        System.out.println( i.letsFindOut() );

        //Error: AmIAnInterfaceWithDefaultImplementation i = new AmIAnInterfaceWithDefaultImplementation();
        //Error: The constructor AmIAnInterfaceWithDefaultImplementation() is not visible
    }
    //Error: public class ImGonnaForceYouToBeAClass extends AmIAnInterfaceWithDefaultImplementation {}
    //Error: The type ImGonnaForceYouToBeAClass cannot subclass the final class AmIAnInterfaceWithDefaultImplementation
}
</code>```

Prints: Default implementation twice.

Here we choose the implementation to provide in a static factory method.  It's only because we're in the same package that the constructor works.

```<code>package trusted;

public class WhoKnowsWhatImplementation {
     public static AmIAnInterfaceWithDefaultImplementation thisProvides() {
        return new AmIAnInterfaceWithDefaultImplementation();
        //return new IAintNoInterfaceNoMore();
    }
}
</code>```

The class below provides both the interface (small i) and the implementation but because the only constructor is protected and the class is final nothing outside the trusted package can force the interface and implementation to stay together.

```<code>package trusted;

/**
 *  Please don't instantiate directly as this may become an Interface.
 *  Use WhoKnowsWhatImplementation
 */
public final class AmIAnInterfaceWithDefaultImplementation {

    protected AmIAnInterfaceWithDefaultImplementation(){}

    public String letsFindOut() {
        return "Default implementation";
    }
}

//public interface AmIAnInterfaceWithDefaultImplementation{
//  public String letsFindOut();
//}
</code>```

We're free to switch to being an interface and push the implementation out to a new class

```<code>package trusted;

//public class IAintNoInterfaceNoMore implements AmIAnInterfaceWithDefaultImplementation {
//
//  @Override
//  public String letsFindOut() {
//      return "Shiny new implementation";
//  }
//}
</code>```

The need for the 'trusted' package comes from a desire not to have the static factory method live on the same class it's instantiating.  It would have to move when we switched to a Java Interface which would impact client code.  That is why the constructor had to be package accessible.

Can you lock this down as a class from outside the trusted package without using reflection?  Is your way of locking it down something that is reasonable to protect against?  What else would you do to protect against getting locked down?  Is there a better approach in java 1.6?

I'd also be interested to know if there is anyway to protect against reflection beyond the java doc begging you not to instantiate it directly but I suspect there isn't.

Many designs fail to adhere to all the design principles. This one violates the open closed principle: classes should be open to extension but closed to modification.  However, this is an attempt to ensure that the classes clients can stay closed even if it changes into a Java Interface.

The example refactoring shown here switches to an interface and implementation class.  It's worth noting that instead it might be decided that the class should actually be abstract.  When we switch to java 1.8, it might even end up as an interface with default methods on it.  The whole point is to preserve the right to make this decision later so we don't have to make it now when we don't know which to do and don't really care.

EDIT: I appreciate all these answers.  Before I accept one, what I'm waiting for is analysis of how vulnerable this approach is to getting locked down to being a class.  I'm willing to accept one that shoots down this whole idea by showing me code that dooms it to forever be a class.  Accepting one that claims it's a sound idea is a nice ego boost but I'd really rather fail here than in the code base.  So convincing me that it's a sound idea is the harder job.

What I've learned from these responses:

Converting from the class to the java interface requires that clients recompile

The class must not expose any more than the java interface could (e.g., no static methods)

Some will insist classes implement Java Interfaces upfront regardless of when they are needed, sigh

The need to recompile the client code strikes me as the most significant issue to be aware of so I'm accepting Maarten Winkels answer.  Thank you all and happy coding.

Body:
First I take program to an interface to mean more of programming to a contract rather than
programming to a literal Java interface.  Contracts can be implemented in classes or interfaces (or even functions).

I want to take advantage of this lack of distinction. I also want to
  interpret the principle "program to an interface" to mean, "I
  shouldn't be able to tell if any client code (using code) is working
  with a java Interface or a java Class". So much so, that later someone
  could swap out the class for a java interface with the same name and
  no client code would need to be touched. That may seem overly strict
  and not exactly what was meant by these design principles (which try
  to be ignorant of java's particular quirks) but I'd love to pull it
  off.

We run into a similar issue at my workplace.  When everything has an interface, I lose sight of what has multiple implementations and what doesn't.  I might not care about things that do have several implementations when writing code.  But I might care when reading code or debugging code.

There are several potential problems with using classes first and refactoring to an interface.

One of the problems I can see is exposing too many public or package (default) access level methods.  If the client can use public or package protected methods that aren't part of the interface, you can't guarantee that you can safely swap an interface in place for the class.

Theoretically a class is serving the purpose of an interface would if it only exposes methods to the outside that would be present in the interface.  If you can be strict with your classes and only expose methods that would be in the interface, then I fail to see how you couldn't swap them out.

Another problem would be a client using direct construction of the class.
However an interface doesn't prevent me from doing this:

 Foo bar = new DefaultFoo();

In order to truly be able to swap instances in and out, you would need Dependency Injection of some flavor.  Also, you may still need to modify client code if you create  multiple implementations.  Something has to know if you wanted a FancyFoo or a PlainFoo for this client.

A final concern would be if the class really implemented more than 1 interface.  You'll find it a lot harder to swap an interface for a class if you have a Frobnicator that implements both the Foo and Bar interfaces.  Clients using Frobnicator might be calling Bar functionality when they only needed a Foo, and vice versa.


问:
Why is object-level privacy difficult to use as a paradigm, and why is it desirable?
I have heard a prominent language designer remark that no language today enforces real object privacy, and we are still unsure whether it is possible in practice to design a language that does.

Without trying to read this particular person's mind, this piqued my interest. There are, I think, two distinct concepts at work here:

Languages with class-level privacy almost always provide ways to work-around it - for example with introspection. Are these workarounds necessary, in that their absence would make certain problems much harder to solve in the language, and if so, doesn't that indicate that the privacy paradigm is flawed? In other words, do people (ab)use these mechanisms when they are provided, and why?

Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter. But why would we want to?

答:
Languages with class-level privacy almost always provide ways to work-around it - for example with introspection. Are these workarounds necessary, in that their absence would make certain problems much harder to solve in the language

Reflection and introspection are particularly useful in white-box testing, so as to ensure code coverage and implementation requirements. For this, access relaxation in reflection is necessary. Language-level tools (depending on the runtime) may also make use of reflection (imagine a native debugger which needs to access private fields).

Some would argue that if a class is properly designed, white-box testing (hence, access relaxation) of the private interface isn't necessary. Since an object's interactions with other objects is defined by its public interface (or, in the case of relatives, its public & protected interfaces), the private interface is immaterial. If the class is so complex as to require testing the private interface to ensure stability, the argument goes, then the class likely has too many responsibilities and should be refactored into multiple classes.

In some cases, casting in C++ can be used to access private fields, but this isn't an intended use.

Inheritance can be used to relax access restrictions, but this isn't a workaround so much as an intersection of access and inheritance rules, and is suggested by the LSP.

and if so, doesn't that indicate that the privacy paradigm is flawed?

Note that white-box tests and debuggers aren't a part of the software's normal execution, so circumventing access rules doesn't (in these cases) negate their purposes.

In other words, do people (ab)use these mechanisms when they are provided, and why?

I'd consider this to be a separate question from the earlier one. People definitely abuse reflection and inheritance to improperly relax access. I'd say typically when it happens it's because there's a design flaw in the program (not the language), but that's more opinion than not.

Casting to circumvent private access is abuse.

Increasing access using inheritance is often (always?) abuse. Sometimes it's another kind of design flaw: naming collision, in this case arising when you override a private base method with an unrelated public method that happens to have the same name & signature.

Class-level privacy is not object-level privacy (an object has access to private state of other objects if they are of the same class), and we don't know how to do the latter.

On the contrary, in Ruby, no instance variable is accessible to another instance, even of the same class; the same goes for private methods. The Ruby term is "instance-private", rather than "object-level private". The same is true of Eiffel and functional-OOP style (where objects are functions that take a message). Smalltalk has instance-private fields, but no true private methods. Scala supports instance-private members.

In general, accessing instance fields outside of an instance isn't syntactically possible in languages that purely use a messaging model rather than a method-call/member-access/slots model, so the former have instance-private fields, though the feature isn't necessarily exclusive to them.

See also "Why are private fields private to the type, not the instance?".

But why would we want to?

The same secondary reason as for all forms of information hiding: anything that can overwrite state is a potential bug source; limiting an object's surface as much as possible helps cut down on the number and locations of potential bugs.


问:
In the light of the open / closed principle, is shared code ownership still important?
I was recently thinking about the following. According to the open / close principle, once a piece of code X has been implemented and tested, it should not be modified any more.

X can still be replaced by another piece of code implementing the same interface (maybe with a better implementation), or new functions and methods can be added to it. But the part that is already implemented and (thoroughly) tested should now work as a black box that can be invoked from the outside but should not be modified any more.

So, if the open / close principle is implemented correctly, shared code ownership should not be so important anymore because no one will need to modify a finished, self-contained piece of code. This seems quite natural to me but I haven't heard of this idea before. Is there any literature or school proposing this thesis: open / close principle makes shared code ownership less important?

答:
The open/closed principal really has nothing to do with code ownership.

Over the course of time, authors and contributors to a code base come and go.  Authors might get promoted into management and not have time to assist with code maintenance and support.  The author might get hit by a bus. Or the author is simply too busy to work on that piece of the software and somebody else will be assigned to work on it.  All of these reasons are part of why shared code ownership is important.  Open/closed doesn't mean other programmers won't look into classes to see what they are doing, especially if trying to debug system behavior.

As for modification, I think one needs to be careful there.  Ideally you shouldn't modify the internals of tested classes.  However, your external requirements can change, or may have been incomplete at the time of writing.  I would rather change the internals of classes to be correct, then have incorrect behavior in classes that I correct through extensions to that class.  In an ideal world, what is in the class internals is correct, you just need to provide more though extension.  But reality sometimes plays out differently.


答:
The cleanest way to do this is to essentially expose an iterator which the caller can use to pull one fixed-size item out at a time.

In C, this can be done like the opendir/readdir/closedir POSIX interface.
The first call allows the library to allocate some opaque iterator context, the second returns the current value from the sequence and advances the iterator, and the last destroys the iterator context.

So, your interface would look something like:

```<code>struct DEVICELIST; /* this is opaque to the caller */
struct Device {
  char description[30];
  /* or whatever data you want to return */
};

struct DEVICELIST *open_devicelist();
int read_device(struct DEVICELIST *, struct Device *current);
void close_devicelist(struct DEVICELIST *);
</code>```

and your client code like:

```<code>struct Device dev;
struct DEVICELIST *dl = open_devicelist();
if (dl == NULL) return;
while (read_device(dl, &dev) == 0) {
    /* data has been copied into dev here, to use for whatever.
       Note it will be overwritten by the next device when we loop round.
    */
}
close_devicelist(dl);
</code>```

If you want something less complex (I know you're just returning a string right now), your second suggestion is much better than the original.

Relying on the user to call your cleanup function is perfectly reasonable, and obviously no worse than the above.

(Note, if you look up the readdir call I mentioned, I'm actually using something more like readdir_r. The original non-reentrant version is a bit icky).

Title: API to get data, caller may not know how much? How to allocate buffer size

Body:
I am writing a C API for retrieving data from a hardware device.  The data will be returned as a string with approximately 30 bytes of text per item.  The problem is there may any number of items.  Could just 10 or there could be 10,000.  So the returned data could range from 10 x 30 = 300 to 10,000 x 30 = 300,000 bytes.

Initially, the function to get the data was like this:

```<code>int get_devicelist(char* devicelist);
</code>```

So the onus is on the caller to know what they are doing and specify a big enough buffer.  Trouble is software using API could be used in many end user applications so the programmer has no end user specific knowledge when they write code to use the API.  The only option then is to specify a buffer (or allocate on heap) that is large enough to hold the largest possible amount of data returned.

So for that reason I am thinking about changing the API as here:

```<code>char* get_devicelist();
void free_devicelist(char* devlist);
</code>```

eg in implementation:

```<code>char* get_devicelist() {
  size_t n = get_devices_size();
  char* devlist = malloc(n * 30);
  if(devlist)
     /* populate devlist */

  return devlist;
}

void free_devicelist(char* devlist) {
   free(devlist);
}
</code>```

Or I just inform users to call free on devlist when no longer needed?

I would change the API code to get the number of devices and then allocate an appropriate amount of memory for devicelist.  The only downside is that the user is then required to call free_devicelist to free the memory allocated.

Is the second API better?  Is there an alternative way?

Body:
The cleanest way to do this is to essentially expose an iterator which the caller can use to pull one fixed-size item out at a time.

In C, this can be done like the opendir/readdir/closedir POSIX interface.
The first call allows the library to allocate some opaque iterator context, the second returns the current value from the sequence and advances the iterator, and the last destroys the iterator context.

So, your interface would look something like:

struct DEVICELIST; /* this is opaque to the caller */
struct Device {
  char description[30];
  /* or whatever data you want to return */
};

struct DEVICELIST *open_devicelist();
int read_device(struct DEVICELIST *, struct Device *current);
void close_devicelist(struct DEVICELIST *);

and your client code like:

struct Device dev;
struct DEVICELIST *dl = open_devicelist();
if (dl == NULL) return;
while (read_device(dl, &dev) == 0) {
    /* data has been copied into dev here, to use for whatever.
       Note it will be overwritten by the next device when we loop round.
    */
}
close_devicelist(dl);

If you want something less complex (I know you're just returning a string right now), your second suggestion is much better than the original.

Relying on the user to call your cleanup function is perfectly reasonable, and obviously no worse than the above.

(Note, if you look up the readdir call I mentioned, I'm actually using something more like readdir_r. The original non-reentrant version is a bit icky).


问:
Are there any known file dispensing algorithms?
I wish to know if there are any known algorithms for dispensing a list of files for a specified maximum directory size (disc size for example), while attempting to keep output directories size close to each other.</p>

答:
This is the classic bin-packing problem.

It is classic because it can be applied to so many tasks that we'd like to optimize but it is computationally NP-hard.


问:
Should putting html tags into localization files be avoided?
We are localizing all parts of our website to many languages. We use XML localization files. I think this scenario is so common, and even there should be a standard solution to this, but still I couldn't find any good advice, and every developer here has different opinion about it, so I'm asking you.

Suggest the following example:

If you have question, please ask our Customer support or write an email to Jane Doe  our specialist.

Or a long, formatted text:

```<code> <p>A very long, marketing blah-blah. A very long, marketing blah-blah. A very long, marketing blah-blah concluding in a list:</p>
 <ul>
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>
</code>```

1) Would you put html tags into the localization XML file?

My concern is the View is separated into 2 files: your page and your localization file. People will forget to check the localization file. Also, there's logic and style embedded in html as well (see target="_blank", or the fact that the above mentioned list is unordered...)

2) Or splitting it to smaller parts?

<msg id="IfYouHaveQuestion">If you have question, please ask our</msg>

<msg id="CustomerSupport">Customer support</msg>

<msg id="OrWrite">or write an email to</msg>
...

Now, View can contain all the markup and style. It's easy to change it, flexible.

But.

There's absolutely no guarantee that the word order will be the same in all languages. Also, this would make the translator's work a nightmare, making it a puzzle.

3) Or introduce BB-style markdown?

<msg id="HaveQuestion">If you have question, please ask our [link url="{customersupportlink}" title="{{CustomerSupportTitle}}">Customer support[/link] or write an email ...</msg>

But probably this is over-complicating the issue, and also we have to write our own parser for this (though, I think it wouldn't be so hard). And probably does not solve the long, formatted text problem.

4) ??? (Your golden solution here) :)

答:
The fact that solution 1 and solution 2 are both less than ideal got me thinking*. Here's an attempt at solution 4 (the "golden" one) that is not just a compromise between 1 and 2.

The goals of this approach are:

Translators work only with natural language

Translators translate meaningful whole sentences, not chopped up parts of speech

Programmers control the markup

The architecture respects the DRY principle

The basic idea is to ask the translators to provide both a complete phrase or sentence, and additional guide phrases that the programmer will use to add markup dynamically.

So looking at your example** where the desired output was

```<code>If you have a question, please ask our
  <a href="..." target="_blank" title="Customer support agent">Customer support agent</a>
or write an email to our specialist,
  <a href="mailto:...">Jane</a>.
</code>```

The translator would provide this XML:

```<code><msg id="IfYouHaveAQuestion_body">
  If you have a question, please ask our Customer support agent or write an email to our specialist, Jane.
</msg>
<msg id="IfYouHaveAQuestion_link">Customer support agent</msg>
<msg id="IfYouHaveAQuestion_email">Jane</msg>
</code>```

Without needing to use markup, the translator is using the second and third strings to specify which parts of the first string should be marked up. Given those hints it's not hard for a coder to assemble the desired output with basic string manipulation methods.

*Solution 3 is not much different than solution 1, but it does have the advantage that BBCode is a more restricted form of markup than HTML.

**Unlike this example, the second example is not a hard case: the list markup should not go into the localization resources.

Body:
The fact that solution 1 and solution 2 are both less than ideal got me thinking*. Here's an attempt at solution 4 (the "golden" one) that is not just a compromise between 1 and 2.

The goals of this approach are:

Translators work only with natural language

Translators translate meaningful whole sentences, not chopped up parts of speech

Programmers control the markup

The architecture respects the DRY principle

The basic idea is to ask the translators to provide both a complete phrase or sentence, and additional guide phrases that the programmer will use to add markup dynamically.

So looking at your example** where the desired output was

If you have a question, please ask our
  <a href="..." target="_blank" title="Customer support agent">Customer support agent</a>
or write an email to our specialist,
  <a href="mailto:...">Jane</a>.

The translator would provide this XML:

<msg id="IfYouHaveAQuestion_body">
  If you have a question, please ask our Customer support agent or write an email to our specialist, Jane.
</msg>
<msg id="IfYouHaveAQuestion_link">Customer support agent</msg>
<msg id="IfYouHaveAQuestion_email">Jane</msg>

Without needing to use markup, the translator is using the second and third strings to specify which parts of the first string should be marked up. Given those hints it's not hard for a coder to assemble the desired output with basic string manipulation methods.

*Solution 3 is not much different than solution 1, but it does have the advantage that BBCode is a more restricted form of markup than HTML.

**Unlike this example, the second example is not a hard case: the list markup should not go into the localization resources.


问:
Inheritance is a null property in the parent a bad practice?
I am not a very experienced programmer. So I ask.

The field in question is the "Amount" field. I store an amount only in a couple levels of the derived class.

The code is a slice of the POCO classes that are making up my data model, the datalayer is Entity framework, code first.

I mention that because the reason I did the amount property like I did is because when I placed the Amount just in a derived class or two and not in the Navigation class, the table in the database would have an extra field for each class with an Amount property, like (Amount, Amount1, Amount2). I did not like that.

So after screwing around with the code for awhile I discovered that...

Placing the Amount property in the navigation class and overriding it in the classes that implemented Amount gave me a table with just one "Amount" field that was Null, unless it was one of the classes that used amount in which case it had a value, which was just what I wanted. I liked that.

So the question is, is the way the Amount property is handled completely proper or have some downside?

```<code>public class Navigation
{
    int Id { get; set; }
    string Title { get; set; }
    string Description { get; set; }
    ObservableCollection<Navigation> Children { get; set; }

    public virtual decimal? Amount
    {
        get { return null; }
        set { value = null; }
    }
}
public class C1 : Navigation { }
public class C2 : Navigation { }
public class C3 : Navigation
{
    private decimal _amount;
    public override decimal? Amount
    {
        get { return _amount; }
        set { if (value != null) _amount = (decimal)value; }
    }
}
public class C4 : Navigation
{
    private decimal _amount;
    public override decimal? Amount
    {
        get { return _amount; }
        set { if (value != null) _amount = (decimal)value; }
    }
}
</code>```

答:
It is a not good practice because people expect something when they see the property in the class. Imagine if someone writes:

```<code>var n = new Navigation (...);
n.Amount = 123.45;
......
Console.WriteLine(n.Amount); //null? why???
</code>```

A better approach would be to at least warn them:

```<code>public virtual decimal Amount{
    get { return new NotSupportedException("Amount is not supported in this class."); }
    set { //same as above }
}
</code>```

But now you'd get the C# practice warning: "properties should behave like fields and should never throw exceptions".

Perhaps you can add a Type field, then throw away inheritance altogether. But I'm not sure if this is appropriate for your scenario (maybe you have lots of extra fields in derived classes).

Of course, if you're not writing a library that will be used by lots of other programmers, there's nothing wrong to bend common practices. Be flexible.

Do you find it confusing to yourself? If it works and you're comfortable with it, go ahead.

What would I do? This is one of the down sides of Entity Framework, which I don't really like anyway. To me, it brings more problems than it solves. I'd just create tables in the DB, create the classes as you wish in C#, then write some helper methods to map them. If all you do is SELECT and INSERT, it's not as hard as you may think. It's outside the scope of this site, but I guarantee you it's around ~50 lines (I've done it).

Body:
It is a not good practice because people expect something when they see the property in the class. Imagine if someone writes:

var n = new Navigation (...);
n.Amount = 123.45;
......
Console.WriteLine(n.Amount); //null? why???

A better approach would be to at least warn them:

public virtual decimal Amount{
    get { return new NotSupportedException("Amount is not supported in this class."); }
    set { //same as above }
}

But now you'd get the C# practice warning: "properties should behave like fields and should never throw exceptions".

Perhaps you can add a Type field, then throw away inheritance altogether. But I'm not sure if this is appropriate for your scenario (maybe you have lots of extra fields in derived classes).

Of course, if you're not writing a library that will be used by lots of other programmers, there's nothing wrong to bend common practices. Be flexible.

Do you find it confusing to yourself? If it works and you're comfortable with it, go ahead.

What would I do? This is one of the down sides of Entity Framework, which I don't really like anyway. To me, it brings more problems than it solves. I'd just create tables in the DB, create the classes as you wish in C#, then write some helper methods to map them. If all you do is SELECT and INSERT, it's not as hard as you may think. It's outside the scope of this site, but I guarantee you it's around ~50 lines (I've done it).