问:
How to refactor my project to have less mutable objects?
There seems to be a trend towards immutable objects, and functional programming. I recently got aware about the benefits of immutability. However, I am not very familiar with this style of programming.

My current classes may have some private or public mutable variables (state variables). I think these variables are the source of mutable state for the objects of my class. If the number of these variables is high, then the state of objects will be more complex. (if there are other reasons for mutable state of the objects of my class, please guide me about them)

Then, my question is how to refactor this class or even redesign my project to have objects with immutable or less complex state.

For example decomposing of the class to other classes with less mutable variables or any other guideline?

Or in other words, I look for some guidelines to design and implement a project to have less mutable objects as possible?

答:
Obvious answer is that you use constructors.

```<code>class A {
public:
   A(int a, int b) : a(a), b(b) {}
private:
   int a, b;
 };
</code>```

If you need to change a or b -variables, the correct course of action is to create new object instead of adding set_a() or set_b() functions.

Body:
Obvious answer is that you use constructors.

class A {
public:
   A(int a, int b) : a(a), b(b) {}
private:
   int a, b;
 };

If you need to change a or b -variables, the correct course of action is to create new object instead of adding set_a() or set_b() functions.


问:
Any way to use VoltDB in rails app?
I've been curiously looking at VoltDB and one year ago I have even seen a gem that was providing Ruby connection to VoltDB. I have checked today again and it seems gone.

I'm planning to go through the "VoltDB University" tutorials but I would really like to know if i'm not wasting my time because it would be super hard to connect to the database if using Rails.

Does anyone have any info on this?

答:
The gem seems to be outdated: https://rubygems.org/gems/voltrb - mentions VoltDB v1.1, last updated in 2010. Initial repository is gone, but here is a clone: https://github.com/Cowen/VoltRb

It uses JSON API, but there is a "VoltDB Client Wire Protocol" which has a specification, so you could try to implement a new client.

ContentLicense: CC BY-SA 3.0

Title: Any way to use VoltDB in rails app?


问:
Is it bad or good to wrap mutable objects in immutable containers?
If I have parts of code that need to mutate the underlying data structure but then others that consume, not mutate the structure, is it good practice to create a wrapper which does not expose mutation operations?

Let's say I have a tree and I only want higher up parts of code to be able to iterate it.

答:
Restriction of access is always a safe approach and can be considered good practice. This is known under the OOP paradigm as encapsulation and exists to prevent programming mistakes which are hard to detect, such as circumventing your own safety precautions in get/set methods by directly changing a variable. This also falls under the broader term of defensive programming, which is a programming paradigm where you eliminate potential errors by making it impossible to commit them in the first place.

There are many different way of achieving this and wrapping portions of code in immutable data structures is definately a viable option, depending on the language.


答:
It's a common approach. Conceptually, this is exactly the same principle as access specifiers and such, namely that you are limiting what operations can be used so that you know that the code is safe.

It can be a lot of effort and confusion to produce wrappers for each possible situation, so it's only really worth it if there's a fairly large body of code that needs this specific subset.

In general, it's always a good thing to restrict methods as much as possible. The only question is how much effort it's worth. This is not a tradeoff that can be made for you without really knowing how much effort it'll cost you and how much code can use it.

Title: Is it bad or good to wrap mutable objects in immutable containers?

Body:
If I have parts of code that need to mutate the underlying data structure but then others that consume, not mutate the structure, is it good practice to create a wrapper which does not expose mutation operations?

Let's say I have a tree and I only want higher up parts of code to be able to iterate it.


答:
Immutability is not an end goal, in and of itself.  Immutability is a tool.  Like all tools, it has its appropriate uses, its advantages and disadvantages.  Achieving it with existing mutable objects is harder than it looks.

Consider an ordinary array:

```<code>var pokerHand = new Cards[5];
</code>```

We can make a data structure using an array as a backing field, and writing an indexer for it:

```<code>public class ImmutableArray<T>
{
    T[] array;

    public this T(int index)
    {
        get { return array[index]; }
    }
}
</code>```

By eliminating the setter from the indexer, you've effectively made member access immutable, right?  Well, not exactly.  Because the item returned by the indexer is a reference type, you can still replace the object held by that reference type, and now you have a new object in that position in the array.

```<code>var item = myPokerHand[5];
item = new Card("KS"); // myPokerHand[5] now contains a new Card
</code>```

To protect the contents of the original array, you have to make a copy of the object, and return that instead.

```<code>    public this T(int index)
    {
        get { return array[index].MemberwiseClone(); } // if you can.
    }
</code>```

Note that MemberwiseClone is a shallow copy, not a deep copy.   Doing this correctly could mean writing a Clone method that faithfully copies all of your object's members, some of which may also be mutable references.

For all of these reasons, it is better to use the immutable collections already provided by the .NET framework, such as ReadOnlyCollection, collections that are designed from the ground up to be immutable.

For your own collections and objects, routinely restricting access to private members is generally a good thing, for reasons that I hope are obvious (cf. encapsulation).

Further Reading

Immutability in C# Part One: Kinds of Immutability

Body:
Immutability is not an end goal, in and of itself.  Immutability is a tool.  Like all tools, it has its appropriate uses, its advantages and disadvantages.  Achieving it with existing mutable objects is harder than it looks.

Consider an ordinary array:

var pokerHand = new Cards[5];

We can make a data structure using an array as a backing field, and writing an indexer for it:

public class ImmutableArray<T>
{
    T[] array;

    public this T(int index)
    {
        get { return array[index]; }
    }
}

By eliminating the setter from the indexer, you've effectively made member access immutable, right?  Well, not exactly.  Because the item returned by the indexer is a reference type, you can still replace the object held by that reference type, and now you have a new object in that position in the array.

var item = myPokerHand[5];
item = new Card("KS"); // myPokerHand[5] now contains a new Card

To protect the contents of the original array, you have to make a copy of the object, and return that instead.

    public this T(int index)
    {
        get { return array[index].MemberwiseClone(); } // if you can.
    }

Note that MemberwiseClone is a shallow copy, not a deep copy.   Doing this correctly could mean writing a Clone method that faithfully copies all of your object's members, some of which may also be mutable references.

For all of these reasons, it is better to use the immutable collections already provided by the .NET framework, such as ReadOnlyCollection, collections that are designed from the ground up to be immutable.

For your own collections and objects, routinely restricting access to private members is generally a good thing, for reasons that I hope are obvious (cf. encapsulation).

Further Reading

Immutability in C# Part One: Kinds of Immutability

ContentLicense: CC BY-SA 4.0


问:
RSpec vs Test::Unit in Rails
I've never been really convinced of the advantages that you get by switching over to RSpec from Test::Unit in Ruby on Rails (despite reading from time to time about RSpec).

What is it about RSpec that most Rails project seems to be using it?

(some code examples clearly indicating advantages of one over the other would be much appreciated)

答:
It's largely a matter of taste, and most testing tools worth their salt support both. My personal preference is for RSpec over Test::Unit because a) the output and layout of the tests focusses on what the object under test is supposed to do (as opposed to what the code is) and b) saying 'X should  Y' makes more sense to me than 'assert that X predicate Y'.

To give you some context for the points above, here's a (pretty contrived) comparison of the output/source code of two functionally equivalent unit tests, one written using RSpec and the other using Test::Unit.

Code under test

```<code>class DeadError < StandardError; end

class Dog
  def bark
    raise DeadError.new "Can't bark when dead" if @dead
    "woof"
  end

  def die
    @dead = true
  end
end
</code>```

Test::Unit

```<code> require 'test/unit'
  require 'dog'

  class DogTest < Test::Unit::TestCase
    def setup
      @dog = Dog.new
    end

    def test_barks
      assert_equal "woof", @dog.bark
    end

    def test_doesnt_bark_when_dead
      @dog.die
      assert_raises DeadError do
        @dog.bark
      end
    end
  end
</code>```

RSpec

```<code>require 'rspec'
require 'dog'

describe Dog do
  before(:all) do
    @dog = Dog.new
  end

  context "when alive" do
    it "barks" do
      @dog.bark.should == "woof"
    end
  end

  context "when dead" do
    before do
      @dog.die
    end

    it "raises an error when asked to bark" do
      lambda { @dog.bark }.should raise_error(DeadError)
    end
  end
end
</code>```

Test::Unit output (as full as I could make it)

```<code>Ξ code/examples → ruby dog_test.rb --verbose
Loaded suite dog_test
Started
test_barks(DogTest): .
test_doesnt_bark_when_dead(DogTest): .

Finished in 0.004937 seconds.
</code>```

RSpec output (documentation formatter)

```<code>Ξ code/examples → rspec -fd dog_spec.rb

Dog
  when alive
    barks
  when dead
    raises an error when asked to bark

Finished in 0.00224 seconds
2 examples, 0 failures

2 tests, 2 assertions, 0 failures, 0 errors
</code>```

P.S. I think Berin (previous responder) is conflating the roles of Cucumber (which grew out of the RSpec project but is independent) and RSpec. Cucumber is a tool for automated acceptance testing in a BDD style, whereas RSpec is a code library for testing which can be, and is, used at unit, integration and functional levels. Hence using RSpec doesn't preclude unit testing - it's just that you call your unit tests 'specs'.

ContentLicense: CC BY-SA 2.5

Title: RSpec vs Test::Unit in Rails

Body:
It's largely a matter of taste, and most testing tools worth their salt support both. My personal preference is for RSpec over Test::Unit because a) the output and layout of the tests focusses on what the object under test is supposed to do (as opposed to what the code is) and b) saying 'X should  Y' makes more sense to me than 'assert that X predicate Y'.

To give you some context for the points above, here's a (pretty contrived) comparison of the output/source code of two functionally equivalent unit tests, one written using RSpec and the other using Test::Unit.

Code under test

class DeadError < StandardError; end

class Dog
  def bark
    raise DeadError.new "Can't bark when dead" if @dead
    "woof"
  end

  def die
    @dead = true
  end
end

Test::Unit

 require 'test/unit'
  require 'dog'

  class DogTest < Test::Unit::TestCase
    def setup
      @dog = Dog.new
    end

    def test_barks
      assert_equal "woof", @dog.bark
    end

    def test_doesnt_bark_when_dead
      @dog.die
      assert_raises DeadError do
        @dog.bark
      end
    end
  end

RSpec

require 'rspec'
require 'dog'

describe Dog do
  before(:all) do
    @dog = Dog.new
  end

  context "when alive" do
    it "barks" do
      @dog.bark.should == "woof"
    end
  end

  context "when dead" do
    before do
      @dog.die
    end

    it "raises an error when asked to bark" do
      lambda { @dog.bark }.should raise_error(DeadError)
    end
  end
end

Test::Unit output (as full as I could make it)

Ξ code/examples → ruby dog_test.rb --verbose
Loaded suite dog_test
Started
test_barks(DogTest): .
test_doesnt_bark_when_dead(DogTest): .

Finished in 0.004937 seconds.

RSpec output (documentation formatter)

Ξ code/examples → rspec -fd dog_spec.rb

Dog
  when alive
    barks
  when dead
    raises an error when asked to bark

Finished in 0.00224 seconds
2 examples, 0 failures

2 tests, 2 assertions, 0 failures, 0 errors

P.S. I think Berin (previous responder) is conflating the roles of Cucumber (which grew out of the RSpec project but is independent) and RSpec. Cucumber is a tool for automated acceptance testing in a BDD style, whereas RSpec is a code library for testing which can be, and is, used at unit, integration and functional levels. Hence using RSpec doesn't preclude unit testing - it's just that you call your unit tests 'specs'.


问:
What is a Developer in Test?
I was recently talking with a recruiter who wants to put me at a company for a position of Developer in Test. He essentially made it sound like a position where you get to fiddle with new programming techniques and test bugs and improvements in software but where you don't need to worry about standard deadlines. You get to be very creative in your work.

But that description was still kinda vague to me. I have been a Web Developer for a number of years now, mostly working in PHP. So I wanted to know if others in the community know more about what these positions typically entail.

I know that this might not be a subject appropriate for this forum, but it was the best fit I could find among Stack Exchange and I would really appreciate it if this wasn't closed since there is really no where else here to ask about it.

I have tried Googling it, but there isn't a lot of information out there. So what exactly is a Developer in Test?

答:
A SDET role is pretty much what you make it, as evidenced by all its different names: QA/Developer, QA Engineer, Automation Developer.  My current title is actually Test Engineer, which I had never heard it called prior to taking this job.  Regardless of the specific title, it is a new position in most companies, so the expectations can be loose.  "Help us automate our testing, and stuff...".  The stuff could include CI tools, API testing, cloud services, integration with internal systems, etc.

Another aspect of the job I don't see in this thread is process improvement.  SDET's typically have been doing QA for a while, and again, typically, they are more technical than the rest of the QA team, including their manager.  They know a lot about the system under test, i.e., "where the bodies are buried".  For these reasons, SDET's tend to get listened to by management, and can have a lot of influence on process--not just testing process, but how the product is built.  Which can be cool, if you're into that.

Title: What is a Developer in Test?


问:
Trouble understanding simple recursion in c
My function:  </p>

```<code>int num(int x)
{
   if(x>0)
     num(x-1);
   else
     return 0;
   printf("%d",x);
}
</code>```

<p>This function takes a input x and prints the numbers from 1 upto x.I can't seem to understand how this works, can someone please elaborate. Thanks in advance! </p>

答:
To solve this type of thing, it's often best to take a pen and paper and "pretend to be the computer running the code".

So, if we have a call of num(4), it will lead to:

```<code>if (4 > 0)    // Yupp, 4 > 0
  num(3);     // x - 1 = 3
  if (3 > 0)  // Yupp
    num(2)
    if (2 > 0)
      num(1)
      if (1 > 0)
        num(0)
        if (0 > 0) // Nope
        goto else-part:
        return 0;
      skip else-part
      print(1);
    skip else-part
    print(2);
  skip else-part
  print(3)
  skip else-part
print(4)
</code>```

Body:
To solve this type of thing, it's often best to take a pen and paper and "pretend to be the computer running the code".

So, if we have a call of num(4), it will lead to:

if (4 > 0)    // Yupp, 4 > 0
  num(3);     // x - 1 = 3
  if (3 > 0)  // Yupp
    num(2)
    if (2 > 0)
      num(1)
      if (1 > 0)
        num(0)
        if (0 > 0) // Nope
        goto else-part:
        return 0;
      skip else-part
      print(1);
    skip else-part
    print(2);
  skip else-part
  print(3)
  skip else-part
print(4)


答:
in my opinion, the easiest way of wrapping your head around recursion is starting from the end.

In every recursive function, there's a stopping condition. In your case it's else return 0; so the method will return 0 if the argument is zero or lower. That's simple. Now let's go backwards.

We know that num(0) returns 0 without doing anything else. So now we can now figure out what num(1) is. num(1) will call num(0) (which will return 0 and do nothing else), and then print x which is 1. Now we can backtrack and look at num(2). num(2) will call num(1), which we already covered, and then prints 2, so we can look at num(3) etc.

So for every number x, num(x) will simply print all numbers from 1 to x.

Title: Trouble understanding simple recursion in c

Body:
My function:  </p>

```<code>int num(int x)
{
   if(x>0)
     num(x-1);
   else
     return 0;
   printf("%d",x);
}
</code>```

<p>This function takes a input x and prints the numbers from 1 upto x.I can't seem to understand how this works, can someone please elaborate. Thanks in advance! </p>


问:
forking boilerplates? or simply cloning them?
Using gitlab/github.

I created boilerplates for all my projects so I've:

wordpress-boilerplate
html5-boilerplate
laravel-boilerplate
ror-boilerplate

I'm debating myself if/when starting a new project I should fork boilerplate and thus save the relationship, or simply export boilerplates and push them to projects own repo.

What is your take on this?

I feel forking is not necessary since I wouldn't be pushing anything back to boilerplates.

Sometimes I think about such unimportant things :(

答:
If you're building a one-off application, I'd recommend cloning the boilerplate, renaming, and building from there.

If you're going to be doing that a lot, and especially if you find yourself starting from the same boilerplate each time but adding certain features repeatedly, then fork the boilerplate, add improvements to your fork, and start new app development projects from your fork of the boilerplate.

The latter has been my approach working with the Roots theming framework for WordPress projects, for instance. I've got my own fork of Roots to which I've added some handy features of my own, and I start new theming projects from my fork.


问:
UML: How to implement a template interface?
Suppose I have an aggregate type and I want to use it in conjunction with a template iterator. The following C# code gives an exact example of my model:

```<code>public interface Iterable<T>
{
    Iterator<T> iterator();
}

public abstract class Letter
{
}

public abstract class Alphabet : Iterable<Letter>
{
    public abstract Iterator<Letter> iterator();
}

public abstract class Iterator<T>
{
    public abstract void first();
    public abstract void next();
    public abstract bool done();
    public abstract T get();
}
</code>```

But I have a little problem when capturing this in UML. The problem is that I'm not sure how to combine two relationships between Alphabet and Iterable: Template Binding and Realisation. I ended up in depicting them separetly but for that I had to introduce two intermediate entities for that and this looks a bit clumsy.

You see these new interface AlphabetIterable (binds Iterable with Letter) and class AlphabetIterator (binds Iterator with Letter).

Is there a way to make an equivalent UML model without these two intermediates?

答:
The picture below shows how Sparx Systems Enterprise Architect's code reverse engineering visualizes the relationship between Alphabet and Iterable when fed with your code snippet.

I've added the «bind» stereotype manually to make it compatible with

www.omg.org/spec/UML/2.5/Beta2 → 7.3.4 Common Structure → Templates → Notation

...

A TemplateBinding is shown as a dashed arrow with the tail on the bound element and the arrowhead on the template and the keyword «bind». The binding information may be displayed as a comma-separated list of template parameter substitutions:

<template-param-substitution> ::= <template-param-name> ‘->’ <actual-template-parameter>

...

See also:

uml-diagrams.org: Template Binding


问:
How to respond to a rude bug report?
I just received a quite rude bug report. The user basically says that we're doing it all wrong using capital letters here and there, although he's in fact just pointing at one bug.

On one hand, I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

What's a decent way of responding? What should I keep in mind? What mindset should I have?

It should be added that the user seems to be a 24 year old CS student, and our product is an Android app that we're giving away free of charge.

答:
What's a decent way of responding? What should I keep in mind? What mindset should I have?

You could keep in mind the Fundamental Attribution Error, which observes that humans tend to see our own mistakes and problems with the viewpoint "I'm fundamentally a good person, but on this occasion I did something wrong", but see other people's mistakes and problems from the view "they are fundamentally a bad person, they always to things wrong".

The complainer is probably not fundamentally evil, nasty and hateful. They are probably a normal human who likes and cares about very similar things that you like. They are a programmer, they found your app, they are interested in whatever your app does, they used it enough to find the bug, they cared enough to report the bug report instead of giving up; but they were angry and lashed out at you.

You are overlap a lot with this person, you have more in common than if they were a 50 year old conspiracy theorist who doesn't know what Android is or what your App does, and sent you a rude email about how you are doing everything wrong by using evil computers.

You wouldn't be bothered by that person at all, would you? It wouldn't strike a nerve, you might even laugh at it.

I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

If you care more about App ratings than about keeping yourself feel good, you are a kind of sell out. If you care more about your users getting a good experience than yourself feeling righteous, you are a kind of sell out.

This is good, not bad. In the context of making your app the best possible app, it's not about you the author, at all. A cathedral builder will have to overcome a lot more problems than hearing some rude words to build a cathedral. A cathedral will stand for hundreds of years and countless people will wonder at it, what does a rude word to the builder in the first moments of it's construction count for? 0.00% of anything. The builders have better things to do than spend effort fighting back, more important things than putdowns.

Is the point to make something as good as you can, or be self-righteous, bitter and nitpicky over small details and individual user accounts?

Is the bug genuine, and can you fix it?

Do you want a world where people respond to anger with anger, or a world where people respond to anger with kindness?

Ideally you would only get polite bug reports. That's not the real world. So would you prefer some rude feedback about bugs, or to not hear about those bugs at all?

If you were rightly or wrongly feeling disappointed and let down by a piece of software and were extremely blunt about it, what kind of reply would you feel good about getting?

Is it really as strong an attack on your App as it feels like? Are you about to lose funding, lose users, fail at your goals completely, have your department shut down, if you don't fight back?

I agree with the "don't take it personally", "be magnanimous" and "fix the bug, ignore the rudeness" people, I just wanted to write more than would fit in a comment about why and how you can frame your thinking to make it completely 'OK' to do that.

-- Edit; actually I want to write more than that --

There's nothing to actually stop you being rude right back. You exist in a post-God world where you don't believe being rude will send you to hell (I assume, otherwise you would have immediately thought about all your religious teachings on how to behave towards others), you are writing a free app so there's no business pressure on you to be unfailingly polite, and you are involved in programming - a pretty relentless technical meritocracy culture with prominent examples of leaders have a rude attitude under the guise of being 'no nonsense', and a culture of flame wars and anger.

In short, there's no higher pressure on you to arm-twist you into a polite reply and you are absolutely free to reply in kind with:

I wrote this for me, if you don't like it, tough.

I wrote this and gave it away for free, how dare think you have any grounds to complain, do you know how much passion I've put into this, I'm so offended right now.

It's open source. Why don't you improve it and submit a patch? Hope this helps. /smug :)

You are an idiot, here's a rant about everything wrong with you and your mother as well.

That was rude so I ignored it, lol. :)

And so on, and there will be no short term immediate consequences whatsoever. Short term, you will feel better. Justified, happy, correct, superior.

So why should you take a personal hit, and feel hurt, feel undervalued, and reply politely in the face of pressure not to?

Because without any higher guiding principle the only thing you can do is step back and ask yourself what kind of a world you want to build. Everything you do is a contribution to the world of the future. Do you want to contribute to a ragey, firey, inhuman, uncaring, technical meritocracy? Or do you want to be a calming, humanising influence, a relatable developer?

I'm leading it towards an obvious conclusion here, but it's not anymore a question of absolute, externally imposed right and wrongness, so maybe you will genuinely land on the other side from where I'm biasing it.

Torvalds swears at incompetent people. Knuth offers money as rewards for correct bug reports. Both are respected and successful.

Title: How to respond to a rude bug report?


问:
Does merely parameterizing a dependency meet the requirements for Inversion of Control?
When I find a concrete dependency inside an extension method, I have been attempting to remove the (concrete) dependency by parameterising it like so

```<code>// original implementation
public static List<Address> GetDuplicate(this Address address)
{
    var repository = new AddressRepository();
    return repository.FindAddress(address.Street, address.Town);
}

// 'Fixed' implementation using 'parameter injection'
public static List<Address> GetDuplicate(this Address address, IAddressRepository repository = null)
{
    repository = repository ?? new AddressRepository();
    return repository.FindAddress(address.Street, address.Town);
}
</code>```

My idea was that this would invert control of the collaborating class, AddressRepository, by making sure it could be passed in by the code using the method.

Anyway when a colleague saw this they said that the code still relied on a concrete implementation and was not using IOC. Although I can see there are some downsides of the code, I'm not sure I agree that it isn't Inversion of Control since

The code depends on an abstraction (IAddressRepository)

Calling code can provide a different implementation.

What principle is violated with respect to IOC? Which part of the code in particular violates that principle? Simply put, is 'parameter injection' actually a thing?

答:
...does the parameterisation of the dependency meet the requirements for "inversion of control"?

No.  That's just Dependency Injection.

Look very carefully at the Wikipedia definition for Inversion of Control:

Inversion of Control (IoC) describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library [or framework].

In traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the reusable code [the library or framework] that calls into the custom, or task-specific, code.

In other words, Inversion of Control is characterized by the Hollywood Principle: Don't call us, we'll call you.

I can think of at least two ways Inversion of Control can occur in everyday use.  One way is by making use of the Subscriber Pattern.  In event-driven UI's, we don't call the UI framework when a user clicks on a button.   Rather, we subscribe to a Click event, and the UI framework calls us:

```<code>// Subscribe to Click event.
this.button1.Click += new System.EventHandler(this.button1_Click);

// Handler for click event
private void button1_Click(object sender, MyEventArgs e)
{
    // Do something when user clicks button
}
</code>```

Another example of Inversion of Control is sort methods that make use of a comparator to determine the behavior of the sort with different data types.  The MSDN documentation for the Linq OrderBy method gives a good example of this.

First, we create a "comparer."  A comparer is a class that satisfies the IComparer interface:

```<code>public class IntegerComparer : IComparer<int>
{
    public int Compare(int i1, int i2)
    {
        return i1 - i2;
    }
}
</code>```

Given an unsorted array of:

```<code>string[] unsortedArray = { "three", "six", "nine", "twelve", "fifteen", "eighteen" };
</code>```

We can then use the comparer to sort the array by the number of characters in each string:

```<code>sortedArray = unsortedArray.OrderBy(a => a.Length, new IntegerComparer());
</code>```

which yields the result:

```<code>six
nine
three
twelve
fifteen
eighteen
</code>```

Once again, we have inverted control by relegating generic behavior to the framework, and having the framework call your custom code to get specific behavior.

Further Reading

Inversion of Control (Martin Fowler's Bliki)

Body:
...does the parameterisation of the dependency meet the requirements for "inversion of control"?

No.  That's just Dependency Injection.

Look very carefully at the Wikipedia definition for Inversion of Control:

Inversion of Control (IoC) describes a design in which custom-written portions of a computer program receive the flow of control from a generic, reusable library [or framework].

In traditional programming, the custom code that expresses the purpose of the program calls into reusable libraries to take care of generic tasks, but with inversion of control, it is the reusable code [the library or framework] that calls into the custom, or task-specific, code.

In other words, Inversion of Control is characterized by the Hollywood Principle: Don't call us, we'll call you.

I can think of at least two ways Inversion of Control can occur in everyday use.  One way is by making use of the Subscriber Pattern.  In event-driven UI's, we don't call the UI framework when a user clicks on a button.   Rather, we subscribe to a Click event, and the UI framework calls us:

// Subscribe to Click event.
this.button1.Click += new System.EventHandler(this.button1_Click);

// Handler for click event
private void button1_Click(object sender, MyEventArgs e)
{
    // Do something when user clicks button
}

Another example of Inversion of Control is sort methods that make use of a comparator to determine the behavior of the sort with different data types.  The MSDN documentation for the Linq OrderBy method gives a good example of this.

First, we create a "comparer."  A comparer is a class that satisfies the IComparer interface:

public class IntegerComparer : IComparer<int>
{
    public int Compare(int i1, int i2)
    {
        return i1 - i2;
    }
}

Given an unsorted array of:

string[] unsortedArray = { "three", "six", "nine", "twelve", "fifteen", "eighteen" };

We can then use the comparer to sort the array by the number of characters in each string:

sortedArray = unsortedArray.OrderBy(a => a.Length, new IntegerComparer());

which yields the result:

six
nine
three
twelve
fifteen
eighteen

Once again, we have inverted control by relegating generic behavior to the framework, and having the framework call your custom code to get specific behavior.

Further Reading

Inversion of Control (Martin Fowler's Bliki)


问:
Is it wise for a high level developer to spend time studying assembly?
It is clear that the knowledge of low level stuff is very important in our work.

But in a situation where you're already developing commercial software on a high level, and when you already have a chosen direction but don't have any assembly skill, isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

When is it too late, and when it is not? And if it is not too late, then how would one go about learning optimally (in the sense of not spending excessive time to get some depth and understanding)?

答:
If you truly have no low-level programming skills, I would highly recommend learning some in your spare time. You don't need to become an expert at it; just reach some level of proficiency. You have to do a lot of the math work yourself, rather than depending on the compiler or libraries to do it for you. It will help you understand readability in programming, since most assembly instructions correspond to one processor instruction. You have to manage the complexity in slightly larger programs yourself, without the benefit of things like if...else. This will help you write simpler high-level programs, because the assembly experience would have taught you how much easier it is to read.

Also, remeber that assembly is not a language! It is a generic term, that basically means the instruction set of a processor that has been abstracted to a symbolic language. Different processors have different instruction sets, and therefore different assembly languages. When you learn 'assembly', you learn a process, not a language.


问:
How to use DDD to solve a common address situation?
This is a simple example to show a situation that I find hard to solve with DDD.

Consider this:
- A property (e.g. a house) has an Address.
- An address can be complete or partial (country only; country and state; country, state and city).
- When a end-user is searching for properties, I need to display a list of all countries.
- When a country is selected, I need to retrieve all related states.
- When a state is selected, I need to retrieve all related cities.

This can be easily done using a data driven approach (querying against a relational model), but when I try to model this, thinking in Domain Driven Design, I'm failing.

I have this obvious constraints:

A city can't exist without a estate.

A estate can't exist without a country.

Conclusion - country is the aggregate root to enforce this constraints.

I'm supposing that address is another aggregate root. But address can only refer to an aggregate root, so how can I refer a partial address? Do I need to think in another root?
When I need to query for city, I need to bring the whole country aggregate root?
And what if I need to search for all cities available for a given string? I need to query for all countries and than transverse through relations?

In this situation, the most obvious solution for me is to have and aggregate root for city, state, country and address. But this is an anemic model.
But to avoid an anemic model, it looks like the only way to solve is having different models. One to insert new cities (using the country aggregate) and others to retrieve and associate those entities. But this smells bad.

I'ts very hard to find a sample that cover a situation like this.
Can someone give me some directions? I'ts fine to recommend a book, but I would love some direct insights.

I read a lot about DDD and I know most of the terms (aggregate, entities, services, associations, value-objects).

答:
You have a good model for handling addresses.  The country state(/province) relationship has worked well for me.  I am not sure it works for all countries.  For the applications I have worked with, I have been unable to normalize the city field.  This results in three tables with cascading foreign key constraints.

```<code>country
state_province
address
</code>```

Searching gets complicated in your case, as you likely want to match cases where only the country or country+state are provided when searching by city.  If you can't normalize city, lookups by city will also be difficult.

Body:
You have a good model for handling addresses.  The country state(/province) relationship has worked well for me.  I am not sure it works for all countries.  For the applications I have worked with, I have been unable to normalize the city field.  This results in three tables with cascading foreign key constraints.

country
state_province
address

Searching gets complicated in your case, as you likely want to match cases where only the country or country+state are provided when searching by city.  If you can't normalize city, lookups by city will also be difficult.


问:
Can I license software under MIT license when using Librarys licensed under the GPL
I'm developing software that i want to license under the MIT License. My software uses libraries licensed under the GPL. I'm NOT recompiling, building, or modifying the Library but I am linking to it. Am i allowed to distribute the package under the MIT license or do i have to distribute the package under the GPL?

The library is actually dual licensed under CDDL 1.1 and GPLv2 with Classpath Exception. Take a look here: https://jsonp.java.net/license.html

答:
Does your library depend on the GPL libraries for its proper functioning?  If it does, then you have created a derived work, and your license must also be GPL.

If your library does not depend on the GPL libraries for its proper functioning, and losing the GPL libraries does not substantially impair your library from working properly, then you should be able to dual-license it.

*I am not a lawyer, and I do not play one on TV.  Void where prohibited.


问:
how to unittest with thorough test coverage
I am trying to get into unit testing with python (though my question
is not specific to python).
I want to add a test for function I already have - I know I should do it
the other way round, but here I am, in need for unit tests for
existing code.

Here is my function:

def my_function(value):
    """
    value: tuple or string
    """
    is_tuple = False
    my_value = value
    if isinstance(value, tuple):
        my_value = value[0]
        is_tuple = True
    return(is_tuple, my_value)
```

<p>Here is my test</p>

<pre class="lang-py prettyprint-override"><code>import unittest
class TestMyFunction(unittest.TestCase):
    def test_my_function(self):
        sv_tupel = my_function(('foo','bar'))
        sv_tupel_res = (True, 'foo')
        sv_single = my_function('foo bar')
        sv_single_res = (False, 'foo bar')
        self.assertEqual(sv_tupel, sv_tupel_res)
        self.assertEqual(sv_single, sv_single_res)
</code>```

Now I have tested two cases of input, but there are of course
a lot more. I could maybe also test if the function fails
if the input is not what it is expected to be.

So my question is, what is the general practice/good practice
to get a thorough test coverage. In this example the
input and output is rather simple and so is the result, but a tested
unit could be more complex. So I wonder how to write a test that
gets all the possible corner cases and input variants
without manually listing them explicitly. Or is that just the way
it has to be? Do people in general just pick a few corner cases,
and add more if it turns out the test was not thorough enough?

Also, for the two cases that I tested, should I write two tests, or is it just
one since it tests one function?

EDIT
I found a partial answer to my question, which helps to build tests that are broader in scope. E.g. you might not need to find all corner cases, but the suite will do it for you: https://hypothesis.readthedocs.org/en/latest/quickstart.html
(Thanks to Raymond Hettinger for tweeting this)

答:
There's no magic formula for thoroughly testing your code. I imagine even for a trivial function, like stringReverse() you can come up with a plethora of edge cases, lots of time thinking/writing tests:

What if the string is null?

What if the string is empty?

What if the string is huge and takes up a large portion of available memory?

What if the string's length is larger than Max Integer? This causes problems on some systems.

What if the string has non-ASCII characters, or indeed the null character in the middle?

Does it preserve case? etc.

The difficulty of completely testing every possible part of your application increases substantially when you consider integration tests.

It's a bit of an art to find the balance between paranoia and apathy here. If you want to test the living hell out of your code, that's really good and laudable. However, even if I told you some sure-fire formula for the "right" degree of code coverage, I'm willing to bet that lack of time or difficulty of testing would cause you to deviate a bit (everyone does).

All that being said, there are guidelines that one could follow. A lot has been written proselytizing how your code should be tested. A good start might be this link: Introduction to Test Driven Development (TDD)


问:
My value checker function needs to return both a boolean and a message
I have a value checking function, something much like a credit card number checking function, that is passed in a string, and needs to check that the value is of the right format.

If it's the right format it needs to return true.

If it's not the right format it needs to return false, and also tell us what's wrong with the value.

The question is, what's the nicest way to achieve this?

Here's a few solutions:

1. Use integer/enum return codes to signify meanings:

```<code>String[] returnCodeLookup =
[
"Value contains wrong number of characters, should contain 10 characters",
"Value should end with 1",
"Value should be a multiple of 3"
]

private int valueChecker(String value)
{
    /*check value*/
    return returnCode;
}

rc = checkValue(valueToBeChecked);
if rc == 0
{
    /*continue as normal*/
}
else
{
    print("Invalid value format: ") + returnCodeLookup[rc];
}
</code>```

I don't like this solution as it it requires implementation on the caller side of things.

2. Create a returnCode class

```<code>Class ReturnCode()
{
    private boolean success;
    private String message;

    public boolean getSuccess()
    {
        return this.success;
    }

    public String getMessage()
    {
        return this.message;
    }
}

private ReturnCode valueChecker(String value)
{
    /*check value*/
    return returnCode;
}

rc = checkValue(valueToBeChecked);
if rc.getSuccess()
{
    /*continue as normal*/
}
else
{
    print("Invalid value format: ") + rc.getMessage();
}
</code>```

This solution is tidy, but it seems like overkill/reinventing the wheel.

3. Use exceptions.

```<code>private boolean valueChecker(String value)
{
    if int(value)%3 != 0 throw InvalidFormatException("Value should be a multiple of 3";
    /*etc*/
    return True;
}

try {
rc = checkValue(valueToBeChecked);
}

catch (InvalidFormatException e)
{
     print e.toString();
}
</code>```

I'm tempted to use this solution, but I'm told that you shouldn't use exceptions for business logic.

答:
None of the above, use a ValueChecker class

First an interface to give you flexibility:

```<code>public interface IValueChecker {
    public boolean checkValue(String value);
    public String getLastMessage();
}
</code>```

Then implement as many valuecheckers as you need:

```<code>public class MyVeryEspecificValueChecker implements IValueChecker {
    private String lastMessage="";
    @Override
    public boolean checkValue(String value) {
        boolean valid=false;
        // perform check, updates "valid" and "lastMessage"
        return valid;
    }
    @Override
    public String getLastMessage() {
        return lastMessage;
    }
}
</code>```

Sample client code:

```<code>public class TestValueChecker {
    public static void main(String[] args) {
        String valueToCheck="213123-YUYAS-27163-10";
        IValueChecker vc = new MyVeryEspecificValueChecker();
        vc.checkValue(valueToCheck);
        System.out.println(vc.getLastMessage());
    }
}
</code>```

It has the advantage that you can have many different value checkers.

Body:
None of the above, use a ValueChecker class

First an interface to give you flexibility:

public interface IValueChecker {
    public boolean checkValue(String value);
    public String getLastMessage();
}

Then implement as many valuecheckers as you need:

public class MyVeryEspecificValueChecker implements IValueChecker {
    private String lastMessage="";
    @Override
    public boolean checkValue(String value) {
        boolean valid=false;
        // perform check, updates "valid" and "lastMessage"
        return valid;
    }
    @Override
    public String getLastMessage() {
        return lastMessage;
    }
}

Sample client code:

public class TestValueChecker {
    public static void main(String[] args) {
        String valueToCheck="213123-YUYAS-27163-10";
        IValueChecker vc = new MyVeryEspecificValueChecker();
        vc.checkValue(valueToCheck);
        System.out.println(vc.getLastMessage());
    }
}

It has the advantage that you can have many different value checkers.


问:
What about LISP, if anything, makes it easier to implement macro systems?
I'm learning Scheme from the SICP and I'm getting the impression that a big part of what makes Scheme and, even more so, LISP special is the macro system. But, since macros are expanded at compile-time, why don't people make equivalent macro systems for C/Python/Java/whatever? For example, one could bind the python command to expand-macros | python or whatever. The code would still be portable to people who don't use the macro system, one would just expand the macros before publishing code. But I don't know of anything like that except templates in C++/Haskell, which I gather aren't really the same. What about LISP, if anything, makes it easier to implement macro systems?

答:
Many Lispers will tell you that what makes Lisp special is homoiconicity, which means that the code's syntax is represented using the same data structures as other data. For example, here's a simple function (using Scheme syntax) for calculating the hypotenuse of a right-angled triangle with the given side lengths:

```<code>(define (hypot x y)
  (sqrt (+ (square x) (square y))))
</code>```

Now, homoiconicity says that the code above is actually representable as a data structure (specifically, lists of lists) in Lisp code. Thus, consider the following lists and see how they "glue" together:

(define #2# #3#)

(hypot x y)

(sqrt #4#)

(+ #5# #6#)

(square x)

(square y)

Macros allow you to treat the source code as just that: lists of stuff. Each of those 6 "sublists" contain either pointers to other lists, or to symbols (in this example: define, hypot, x, y, sqrt, +, square).

So, how can we use homoiconicity to "pick apart" syntax and make macros? Here's a simple example. Let's reimplement the let macro, which we'll call my-let. As a reminder,

```<code>(my-let ((foo 1)
         (bar 2))
  (+ foo bar))
</code>```

should expand into

```<code>((lambda (foo bar)
   (+ foo bar))
 1 2)
</code>```

Here's an implementation using Scheme "explicit renaming" macros†:

```<code>(define-syntax my-let
  (er-macro-transformer
    (lambda (form rename compare)
      (define bindings (cadr form))
      (define body (cddr form))
      `((,(rename 'lambda) ,(map car bindings)
          ,@body)
        ,@(map cadr bindings)))))
</code>```

The form parameter is bound to the actual form, so for our example, it would be (my-let ((foo 1) (bar 2)) (+ foo bar)). So, let's work through the example:

First, we retrieve the bindings from the form. cadr grabs the ((foo 1) (bar 2)) portion of the form.

Then, we retrieve the body from the form. cddr grabs the ((+ foo bar)) portion of the form. (Note that this is intended to grab all the subforms after the binding; so if the form were

```<code>(my-let ((foo 1)
         (bar 2))
  (debug foo)
  (debug bar)
  (+ foo bar))
</code>```

then the body would be ((debug foo) (debug bar) (+ foo bar)).)

Now, we actually build the resultant lambda expression and call using the bindings and body we have collected. The backtick is called a "quasiquote", which means to treat everything inside the quasiquote as literal datums, except the bits after the commas ("unquote").

The (rename 'lambda) means to use the lambda binding in force when this macro is defined, rather than whatever lambda binding might be around when this macro is used. (This is known as hygiene.)

(map car bindings) returns (foo bar): the first datum in each of the bindings.

(map cadr bindings) returns (1 2): the second datum in each of the bindings.

,@ does "splicing", which is used for expressions that return a list: it causes the list's elements to be pasted into the result, rather than the list itself.

Putting all that together, we get, as a result, the list (($lambda (foo bar) (+ foo bar)) 1 2), where $lambda here refers to the renamed lambda.

Straightforward, right? ;-) (If it's not straightforward for you, just imagine how difficult it would be to implement a macro system for other languages.)

So, you can have macro systems for other languages, if you have a way to be able to "pick apart" source code in a non-clunky way. There are some attempts at this. For example, sweet.js does this for JavaScript.

† For seasoned Schemers reading this, I intentionally chose to use explicit renaming macros as a middle compromise between defmacros used by other Lisp dialects, and syntax-rules (which would be the standard way to implement such a macro in Scheme). I don't want to write in other Lisp dialects, but I don't want to alienate non-Schemers who aren't used to syntax-rules.

For reference, here's the my-let macro that uses syntax-rules:

```<code>(define-syntax my-let
  (syntax-rules ()
    ((my-let ((id val) ...)
       body ...)
     ((lambda (id ...)
        body ...)
      val ...))))
</code>```

The corresponding syntax-case version looks very similar:

```<code>(define-syntax my-let
  (lambda (stx)
    (syntax-case stx ()
      ((_ ((id val) ...)
         body ...)
       #'((lambda (id ...)
            body ...)
          val ...)))))
</code>```

The difference between the two is that everything in syntax-rules has an implicit #' applied, so you can only have pattern/template pairs in syntax-rules, hence it's fully declarative. In contrast, in syntax-case, the bit after the pattern is actual code that, in the end, has to return a syntax object (#'(...)), but can contain other code too.

Body:
Many Lispers will tell you that what makes Lisp special is homoiconicity, which means that the code's syntax is represented using the same data structures as other data. For example, here's a simple function (using Scheme syntax) for calculating the hypotenuse of a right-angled triangle with the given side lengths:

(define (hypot x y)
  (sqrt (+ (square x) (square y))))

Now, homoiconicity says that the code above is actually representable as a data structure (specifically, lists of lists) in Lisp code. Thus, consider the following lists and see how they "glue" together:

(define #2# #3#)

(hypot x y)

(sqrt #4#)

(+ #5# #6#)

(square x)

(square y)

Macros allow you to treat the source code as just that: lists of stuff. Each of those 6 "sublists" contain either pointers to other lists, or to symbols (in this example: define, hypot, x, y, sqrt, +, square).

So, how can we use homoiconicity to "pick apart" syntax and make macros? Here's a simple example. Let's reimplement the let macro, which we'll call my-let. As a reminder,

(my-let ((foo 1)
         (bar 2))
  (+ foo bar))

should expand into

((lambda (foo bar)
   (+ foo bar))
 1 2)

Here's an implementation using Scheme "explicit renaming" macros†:

(define-syntax my-let
  (er-macro-transformer
    (lambda (form rename compare)
      (define bindings (cadr form))
      (define body (cddr form))
      `((,(rename 'lambda) ,(map car bindings)
          ,@body)
        ,@(map cadr bindings)))))

The form parameter is bound to the actual form, so for our example, it would be (my-let ((foo 1) (bar 2)) (+ foo bar)). So, let's work through the example:

First, we retrieve the bindings from the form. cadr grabs the ((foo 1) (bar 2)) portion of the form.

Then, we retrieve the body from the form. cddr grabs the ((+ foo bar)) portion of the form. (Note that this is intended to grab all the subforms after the binding; so if the form were

(my-let ((foo 1)
         (bar 2))
  (debug foo)
  (debug bar)
  (+ foo bar))

then the body would be ((debug foo) (debug bar) (+ foo bar)).)

Now, we actually build the resultant lambda expression and call using the bindings and body we have collected. The backtick is called a "quasiquote", which means to treat everything inside the quasiquote as literal datums, except the bits after the commas ("unquote").

The (rename 'lambda) means to use the lambda binding in force when this macro is defined, rather than whatever lambda binding might be around when this macro is used. (This is known as hygiene.)

(map car bindings) returns (foo bar): the first datum in each of the bindings.

(map cadr bindings) returns (1 2): the second datum in each of the bindings.

,@ does "splicing", which is used for expressions that return a list: it causes the list's elements to be pasted into the result, rather than the list itself.

Putting all that together, we get, as a result, the list (($lambda (foo bar) (+ foo bar)) 1 2), where $lambda here refers to the renamed lambda.

Straightforward, right? ;-) (If it's not straightforward for you, just imagine how difficult it would be to implement a macro system for other languages.)

So, you can have macro systems for other languages, if you have a way to be able to "pick apart" source code in a non-clunky way. There are some attempts at this. For example, sweet.js does this for JavaScript.

† For seasoned Schemers reading this, I intentionally chose to use explicit renaming macros as a middle compromise between defmacros used by other Lisp dialects, and syntax-rules (which would be the standard way to implement such a macro in Scheme). I don't want to write in other Lisp dialects, but I don't want to alienate non-Schemers who aren't used to syntax-rules.

For reference, here's the my-let macro that uses syntax-rules:

(define-syntax my-let
  (syntax-rules ()
    ((my-let ((id val) ...)
       body ...)
     ((lambda (id ...)
        body ...)
      val ...))))

The corresponding syntax-case version looks very similar:

(define-syntax my-let
  (lambda (stx)
    (syntax-case stx ()
      ((_ ((id val) ...)
         body ...)
       #'((lambda (id ...)
            body ...)
          val ...)))))

The difference between the two is that everything in syntax-rules has an implicit #' applied, so you can only have pattern/template pairs in syntax-rules, hence it's fully declarative. In contrast, in syntax-case, the bit after the pattern is actual code that, in the end, has to return a syntax object (#'(...)), but can contain other code too.


答:
Homoiconicity makes it much much easier to implement macros. The idea that code is data and data is code makes it possible to more or less (barring accidental capture of identifiers, solved by hygienic macros) to freely substitute one for the other. Lisp and Scheme make this easier with their syntax of S-expressions which are uniformly structured and thus easy to turn into ASTs which form the basis of Syntactic Macros.

Languages without S-Expressions or Homoiconicity will run into trouble implementing Syntactic Macros though it can still certainly be done. Project Kepler is attempting to introduce them to Scala for instance.

The largest issue with syntax macros usage aside from non-homoiconicity, is the issue of arbitrarily generated syntax. They offer tremendous flexibility and power but at the price that your source code may no longer be as easy to understand or maintain.

Body: I'm learning Scheme from the SICP and I'm getting the impression that a big part of what makes Scheme and, even more so, LISP special is the macro system. But, since macros are expanded at compile-time, why don't people make equivalent macro systems for C/Python/Java/whatever? For example, one could bind the python command to expand-macros | python or whatever. The code would still be portable to people who don't use the macro system, one would just expand the macros before publishing code. But I don't know of anything like that except templates in C++/Haskell, which I gather aren't really the same. What about LISP, if anything, makes it easier to implement macro systems?


答:
Yes, encapsulation and immutability are good, but it's important to understand why, because you're sort of hitting just the wrong spot as Erik Meijer describes in his paper subtitled "Mostly functional" programming does not work.

Encapsulation is good when it works to decouple an interface from its implementation.  It stops being good when you look at it to be some sort of security system protecting your public data from all those evil programmers down the hall who write the calling code.  What often ends up happening in that situation is more code needs the unrestricted reference than you anticipated, and you end up with a lot of hacks converting it back and forth, or with the one unrestricted class trying to do way too much.

Immutability has a great number of benefits, nearly all of which disappear when you try to do it halfway.  For example, you won't be able to change the tree without resetting every iterator in every thread currently accessing it.

You're really better off just making it immutable all the way down.  This lets you take advantage of all the benefits of immutability, and you won't care who has access to the insert/delete API, because they're only changing their version of the tree.


答:
Use a more complex return object that encapsulates both concerns. Example:

```<code>public interface IValidationResult {
  boolean isSuccess();
  String getMessage();
}
</code>```

This has several advantages:

Returns multiple related pieces of data in one object.

Room for expansion if you need to add additional data in the future.

No reliance on temporal coupling: you can validate multiple inputs and they do not clobber the message as in the other answer. You can check messages in any order, across threads even.

I have actually used this specific design before, in applications where a validation may be more than simply true or false. Perhaps a detailed message is necessary, or only part of the input is invalid (e.g. a form with ten elements might only have one or two invalid fields). Using this design, you can easily accommodate those requirements.

Title: My value checker function needs to return both a boolean and a message

Body:
I have a value checking function, something much like a credit card number checking function, that is passed in a string, and needs to check that the value is of the right format.

If it's the right format it needs to return true.

If it's not the right format it needs to return false, and also tell us what's wrong with the value.

The question is, what's the nicest way to achieve this?

Here's a few solutions:

1. Use integer/enum return codes to signify meanings:

```<code>String[] returnCodeLookup =
[
"Value contains wrong number of characters, should contain 10 characters",
"Value should end with 1",
"Value should be a multiple of 3"
]

private int valueChecker(String value)
{
    /*check value*/
    return returnCode;
}

rc = checkValue(valueToBeChecked);
if rc == 0
{
    /*continue as normal*/
}
else
{
    print("Invalid value format: ") + returnCodeLookup[rc];
}
</code>```

I don't like this solution as it it requires implementation on the caller side of things.

2. Create a returnCode class

```<code>Class ReturnCode()
{
    private boolean success;
    private String message;

    public boolean getSuccess()
    {
        return this.success;
    }

    public String getMessage()
    {
        return this.message;
    }
}

private ReturnCode valueChecker(String value)
{
    /*check value*/
    return returnCode;
}

rc = checkValue(valueToBeChecked);
if rc.getSuccess()
{
    /*continue as normal*/
}
else
{
    print("Invalid value format: ") + rc.getMessage();
}
</code>```

This solution is tidy, but it seems like overkill/reinventing the wheel.

3. Use exceptions.

```<code>private boolean valueChecker(String value)
{
    if int(value)%3 != 0 throw InvalidFormatException("Value should be a multiple of 3";
    /*etc*/
    return True;
}

try {
rc = checkValue(valueToBeChecked);
}

catch (InvalidFormatException e)
{
     print e.toString();
}
</code>```

I'm tempted to use this solution, but I'm told that you shouldn't use exceptions for business logic.

Body:
Use a more complex return object that encapsulates both concerns. Example:

public interface IValidationResult {
  boolean isSuccess();
  String getMessage();
}

This has several advantages:

Returns multiple related pieces of data in one object.

Room for expansion if you need to add additional data in the future.

No reliance on temporal coupling: you can validate multiple inputs and they do not clobber the message as in the other answer. You can check messages in any order, across threads even.

I have actually used this specific design before, in applications where a validation may be more than simply true or false. Perhaps a detailed message is necessary, or only part of the input is invalid (e.g. a form with ten elements might only have one or two invalid fields). Using this design, you can easily accommodate those requirements.


答: You may license and distribute your application code under the MIT license, however you may not distribute binaries. Essentially you must let your users build their own binaries using their own copy of the GPLed library.</p>

Title: Can I license software under MIT license when using Librarys licensed under the GPL

Body:
I'm developing software that i want to license under the MIT License. My software uses libraries licensed under the GPL. I'm NOT recompiling, building, or modifying the Library but I am linking to it. Am i allowed to distribute the package under the MIT license or do i have to distribute the package under the GPL?

The library is actually dual licensed under CDDL 1.1 and GPLv2 with Classpath Exception. Take a look here: https://jsonp.java.net/license.html


问:
Convince Windows SmartScreen and web browser that my application is safe?
I am developing a Free and Open-Source software (C++). When I download my own application from a web link, Microsoft Smart Screen and Google Chrome are getting in the way since it comes from and "Unknown Publisher".

What are my options to spare my future users from this warning?

答:
You have to buy a "Code Signing Certificate". Vendors include Comodo or Godaddy, it costs about $150 to $200. You can make installation packages with it for 1 year. The installation package itself has no expiration date (also look up timestamp option).

Some famous freeware products don't have certificates, but they are allowed through because lots of people download them so they are trusted. With your product, you have to convince lots of people to download them until smart screen eventually leaves it alone.

Alternatively, you can put your product in a zip package, but Windows still gives it a hard time.


答:
A dissenting opinion:  Lisp's homoiconicity is far less of a useful thing than most Lisp fans would have you believe.

To understand syntactic macros, it's important to understand compilers.  The job of a compiler is to turn human-readable code into executable code.  From a very high-level perspective, this has two overall phases: parsing and code generation.

Parsing is the process of reading code, interpreting it according to a set of formal rules, and transforming it into a tree structure, generally known as an AST (Abstract Syntax Tree).  For all the diversity among programming languages, this is one remarkable commonality: essentially every general-purpose programming language parses into a tree structure.

Code generation takes the parser's AST as its input, and transforms it into executable code via the application of formal rules.  From a performance perspective, this is a much simpler task; many high-level language compilers spend 75% or more of their time on parsing.

The thing to remember about Lisp is that it's very, very old.  Among programming languages, only FORTRAN is older than Lisp.  Way back in the day, parsing (the slow part of compiling) was considered a dark and mysterious art.  John McCarthy's original papers on the theory of Lisp (back when it was just an idea that he never thought could actually be implemented as a real computer programming language) describes a somewhat more complex and expressive syntax than the modern "S-expressions everywhere for everything" notation.  That came about later, when people were trying to actually implement it.  Because parsing was not well-understood back then, they basically punted on it and dumbed down the syntax into a homoiconic tree structure in order to make the parser's job utterly trivial.  The end result is that you (the developer) have to do a lot of the parser's work for it by writing the formal AST directly into your code.  Homoiconicity doesn't "make macros so much easier" as much as it makes writing everything else that much harder!

The problem with this is that, especially with dynamic typing, it's very difficult for S-expressions to carry much semantic information around with them.  When all of your syntax is the same type of thing (lists of lists), there isn't much in the way of context provided by the syntax, and so the macro system has very little to work with.

Compiler theory has come a long way since the 1960s when Lisp was invented, and while the things it accomplished were impressive for its day, they look rather primitive now.  For an example of a modern metaprogramming system, have a look at the (sadly underappreciated) Boo language.  Boo is statically typed, object-oriented, and open-source, so every AST node has a type with a well-defined structure that a macro developer can read the code to.  The language has a relatively simple syntax inspired by Python, with various keywords that give intrinsic semantic meaning to the tree structures built from them, and its metaprogramming has an intuitive quasiquote syntax to simplify the creation of new AST nodes.

Here's a macro I created yesterday when I realized I was applying the same pattern to a bunch of different places in GUI code, where I would call BeginUpdate() on a UI control, perform an update in a try block, and then call EndUpdate():

```<code>macro UIUpdate(value as Expression):
    return [|
        $value.BeginUpdate()
        try:
            $(UIUpdate.Body)
        ensure:
            $value.EndUpdate()
    |]
</code>```

The macro command is, in fact, a macro itself, one that takes a macro body as input and generates a class to process the macro.  It uses the name of the macro as a variable that stands in for the MacroStatement AST node that represents the macro invocation.  The [| ... |] is a quasiquote block, generating the AST that corresponds to the code within, and inside the quasiquote block, the $ symbol provides the "unquote" facility, substituting in a node as specified.

With this, it's possible to write:

```<code>UIUpdate myComboBox:
   LoadDataInto(myComboBox)
   myComboBox.SelectedIndex = 0
</code>```

and have it expand to:

```<code>myComboBox.BeginUpdate()
try:
   LoadDataInto(myComboBox)
   myComboBox.SelectedIndex = 0
ensure:
   myComboBox.EndUpdate()
</code>```

Expressing the macro this way is simpler and more intuitive than it would be in a Lisp macro, because the developer knows the structure of MacroStatement and knows how the Arguments and Body properties work, and that inherent knowledge can be used to express the concepts involved in a very intuitive way.  It's also safer, because the compiler knows the structure of MacroStatement, and if you try to code something that isn't valid for a MacroStatement, the compiler will catch it right away and report the error instead of you not knowing until something blows up on you at runtime.

Grafting macros onto Haskell, Python, Java, Scala, etc isn't difficult because these languages aren't homoiconic; it's difficult because the languages are not designed for them, and it works best when your language's AST hierarchy is designed from the ground up to be examined and manipulated by a macro system.  When you're working with a language that was designed with metaprogramming in mind from the beginning, macros are much simpler and easier to work with!

Title: What about LISP, if anything, makes it easier to implement macro systems?

Body:
A dissenting opinion:  Lisp's homoiconicity is far less of a useful thing than most Lisp fans would have you believe.

To understand syntactic macros, it's important to understand compilers.  The job of a compiler is to turn human-readable code into executable code.  From a very high-level perspective, this has two overall phases: parsing and code generation.

Parsing is the process of reading code, interpreting it according to a set of formal rules, and transforming it into a tree structure, generally known as an AST (Abstract Syntax Tree).  For all the diversity among programming languages, this is one remarkable commonality: essentially every general-purpose programming language parses into a tree structure.

Code generation takes the parser's AST as its input, and transforms it into executable code via the application of formal rules.  From a performance perspective, this is a much simpler task; many high-level language compilers spend 75% or more of their time on parsing.

The thing to remember about Lisp is that it's very, very old.  Among programming languages, only FORTRAN is older than Lisp.  Way back in the day, parsing (the slow part of compiling) was considered a dark and mysterious art.  John McCarthy's original papers on the theory of Lisp (back when it was just an idea that he never thought could actually be implemented as a real computer programming language) describes a somewhat more complex and expressive syntax than the modern "S-expressions everywhere for everything" notation.  That came about later, when people were trying to actually implement it.  Because parsing was not well-understood back then, they basically punted on it and dumbed down the syntax into a homoiconic tree structure in order to make the parser's job utterly trivial.  The end result is that you (the developer) have to do a lot of the parser's work for it by writing the formal AST directly into your code.  Homoiconicity doesn't "make macros so much easier" as much as it makes writing everything else that much harder!

The problem with this is that, especially with dynamic typing, it's very difficult for S-expressions to carry much semantic information around with them.  When all of your syntax is the same type of thing (lists of lists), there isn't much in the way of context provided by the syntax, and so the macro system has very little to work with.

Compiler theory has come a long way since the 1960s when Lisp was invented, and while the things it accomplished were impressive for its day, they look rather primitive now.  For an example of a modern metaprogramming system, have a look at the (sadly underappreciated) Boo language.  Boo is statically typed, object-oriented, and open-source, so every AST node has a type with a well-defined structure that a macro developer can read the code to.  The language has a relatively simple syntax inspired by Python, with various keywords that give intrinsic semantic meaning to the tree structures built from them, and its metaprogramming has an intuitive quasiquote syntax to simplify the creation of new AST nodes.

Here's a macro I created yesterday when I realized I was applying the same pattern to a bunch of different places in GUI code, where I would call BeginUpdate() on a UI control, perform an update in a try block, and then call EndUpdate():

macro UIUpdate(value as Expression):
    return [|
        $value.BeginUpdate()
        try:
            $(UIUpdate.Body)
        ensure:
            $value.EndUpdate()
    |]

The macro command is, in fact, a macro itself, one that takes a macro body as input and generates a class to process the macro.  It uses the name of the macro as a variable that stands in for the MacroStatement AST node that represents the macro invocation.  The [| ... |] is a quasiquote block, generating the AST that corresponds to the code within, and inside the quasiquote block, the $ symbol provides the "unquote" facility, substituting in a node as specified.

With this, it's possible to write:

UIUpdate myComboBox:
   LoadDataInto(myComboBox)
   myComboBox.SelectedIndex = 0

and have it expand to:

myComboBox.BeginUpdate()
try:
   LoadDataInto(myComboBox)
   myComboBox.SelectedIndex = 0
ensure:
   myComboBox.EndUpdate()

Expressing the macro this way is simpler and more intuitive than it would be in a Lisp macro, because the developer knows the structure of MacroStatement and knows how the Arguments and Body properties work, and that inherent knowledge can be used to express the concepts involved in a very intuitive way.  It's also safer, because the compiler knows the structure of MacroStatement, and if you try to code something that isn't valid for a MacroStatement, the compiler will catch it right away and report the error instead of you not knowing until something blows up on you at runtime.

Grafting macros onto Haskell, Python, Java, Scala, etc isn't difficult because these languages aren't homoiconic; it's difficult because the languages are not designed for them, and it works best when your language's AST hierarchy is designed from the ground up to be examined and manipulated by a macro system.  When you're working with a language that was designed with metaprogramming in mind from the beginning, macros are much simpler and easier to work with!


问:
PHP extended class method requires same signature including object class requirement?
Not sure exactly how to phrase the question succinctly for the title.

I have a collection class that extends another collection class.

The parent collection-class has a method addMember(someClass $obj) that adds an object to the collection.

The child collection-class groups objects of the child class of someclass, someClassChild. I thought that a child class's method's signature would pass muster as long as the signature was the same or required children of the classes the parent required.

E.g. addMember(someClassChild $obj)

But I tried it and I'm getting a warning about strict standards.

So then, how to I implement a collection class as a child of another collection class to provide functionality for parent/child base objects?

答: The principle you're looking for is covariance and contravariance in type hints. To my knowledge, PHP doesn't support it.</p>


问:
Is there a canonical book on Ruby on Rails?
I'm an experienced developer with .NET, and understand core computing concepts well (OOP, design patterns, etc) but would like to also learn rails.

Is there a book out there that's the de-facto standard for describing best practices, design methodologies, and other helpful information on Ruby on Rails? What about that book makes it special?

答:
Agile Web Development with Rails will bring you  up to speed at a relatively rapid pace.

For learning the ins and outs of the Ruby language itself, I found Programming Ruby 1.9 helpful.

Between those two books you'll know what you need to know to get going.

If you are looking for free and online, Ruby on Rails Tutorial isn't bad at all.


问:
What is a peer in computer network?
From Tanebaum's Computer Network:

A five-layer network is illustrated in Fig. 1-13. The entities comprising the
  corresponding layers on different machines are called peers. The peers may be software processes, hardware devices, or even human beings. In other words, it is
  the peers that communicate by using the protocol to talk to each other.

I don't understand what a peer is, because the usage of English word "comprising" can be ambiguous ( A whole comprises parts. Parts comprise a whole.)

Can you point/circle out what part in Figure 1-13 is a peer?

Are a peer and a host in the figure the same concept?

Thanks.

答:
In figure 1-13, there are many peers.

Host 1, Layer 5 is a peer to Host 2, Layer 5.

Host 1, Layer 4 is a peer to Host 2, Layer 4.

Host 1, Layer 3 is a peer to Host 2, Layer 3.

Host 1, Layer 2 is a peer to Host 2, Layer 2.

Host 1, Layer 1 is a peer to Host 2, Layer 1.

Note that it is commutative, so for example,

Host 2, Layer 5 is a peer to Host 1, Layer 5.

But to make sure you don't misunderstand, a peer is not always a layer.  If I talk to you on a telephone, you and I are peers in that communication.

In the same telephone call, let's say they are mobile phones.  The mobile phones each convert the audio to/from radio waves to a tower.  In this case, the mobile phones are peers on the phone network.

However, in the same example, I am not a peer with your mobile phone because we are on different levels.

I hope this clears it up.

Title: What is a peer in computer network?


问:
Is it bad or good to wrap mutable objects in immutable containers?
If I have parts of code that need to mutate the underlying data structure but then others that consume, not mutate the structure, is it good practice to create a wrapper which does not expose mutation operations?

Let's say I have a tree and I only want higher up parts of code to be able to iterate it.

答:
Immutability has two effects: One, I cannot modify an immutable object. Two, nobody can modify an immutable object behind my back. If you hand me an immutable container containing a mutable object, then you can still modify that mutable object in the immutable container behind my back, so I gain nothing from the fact that it is immutable. You'd have to guarantee that once you create the immutable container, you are not going to modify the object anymore. </p>

<p>On the other hand, you can discuss whether an immutable container of mutable objects is really "immutable". Like an immutable array of strings, where I can rely that the array will always contain the same strings, but I cannot rely on what the mutable strings contain. For many situations, that kind of immutability doesn't actually give the guarantees that a consumer needs. </p>

Body:
Immutability has two effects: One, I cannot modify an immutable object. Two, nobody can modify an immutable object behind my back. If you hand me an immutable container containing a mutable object, then you can still modify that mutable object in the immutable container behind my back, so I gain nothing from the fact that it is immutable. You'd have to guarantee that once you create the immutable container, you are not going to modify the object anymore.

On the other hand, you can discuss whether an immutable container of mutable objects is really "immutable". Like an immutable array of strings, where I can rely that the array will always contain the same strings, but I cannot rely on what the mutable strings contain. For many situations, that kind of immutability doesn't actually give the guarantees that a consumer needs.


问:
Technique to synchronize error codes in a same-project-API
In the project I am working right now, we have some python and some C# code. At some point, I call from python a subprocess which starts a C# executable. This C# code returns an error code, which has to be understood on the python side and a readable report has to be created.

This means, both sides "must speak the same language". So, at the end I have to handle a mapping {error codes: readable explanation} (normally we implement this as static properties of a enumeration class). This is of course a case of code duplication, and prone to be inconsistent.

My ideas to mitigate this have been so far:

Automatically generate code: let's say when the mapping on the C# part changes, the code will be parsed and automatically generated on the the python side. While I think this is technically quite correct, I have to somehow parse C# code and translate it to valid python code, which is something probably hard to get it right at the first time.

Partial processing of error code on the python side. This means, just check for zero or non-zero return value, and if non-zero, read the stdout of the C# process and report it, no matter what. While this is very easy to implement, I see some possible caveats, like the C# process crashing in an unexpected way and reporting some exception traceback or similar.

Since this must be a quite common problem, I would like to know what are the easiest and more maintainable approaches used in the industry.

答: Rather than parsing C# code, my suggestion would be to store the error codes and their associated descriptions in external resource files (XML, JSON, CSV, database table, whatever). That way all the Python code has to do is look up the code and retrieve the human-readable description. This will also allow you to add localization/translation support or update texts without redeploying code.</p>


问:
Paired Programming - best approach
There is a new developer starting soon.  This person is at an entry level but has worked in app support for a couple of years.

I asked this question some time ago just before I started training someone else: Is Pair Programming also used to train less experienced developers and bring them up to speed?.  However, they were moved onto another project so it did not really go ahead.

My question is: How often should these sessions go ahead? From answers to my previous question I believe there are two approaches:

1) Spend one week training the person and come up with some objectives.  Then three months later have another one week session and set some more objectives.
2) Spend one morning per week on paired programming.  This would give me time to spend elsewhere.

Also this developer is "green" (term I took from an answer to my previous question), whereas I have worked as a developer for my current employer for seven years.  Unfortunately I am the only developer.  Is there any other approaches to knowledge transfer that work when the learner is "green" and the teacher is more experienced?

答:
I've done my share of pair programming and training rookies. First of all, it really depends on actual talent. Some developers will never grasp abstract thinking and are most happy developing basic features or executing basic programming tasks.
Others will want to dive into the full code base of the applications you're building and contribute to architecture.

If you're dealing with the first type of developer, you probably want to keep relatively short sessions and have them often (maybe even every day for an hour or so). If you have the latter, you want to have longer sessions, but include whiteboard sessions for design as well. Keep in mind that the task you're trying to get accomplished has to be suitable to a pair programming session.

Title: Paired Programming - best approach


问:
How to approach refactoring an existing web application?
I've been reading and thinking a lot lately, and I've come to the conclusion that I maybe I should rethink my web development strategy. I'm doing a lot of on-the-fly programming, and in the 2 years I've been working on a PHP web application, what might have begun as a little tool became quite the big project. But there is a ton of legacy code from me and my predecessor, snippet of code that might have make sense at the time, but now I'm questioning the usefulness of said code in the form it is actually. Furthermore so such things like unit testing and Test-Driven Development wasn't in my scope until quite recently.

So how would you approach refactoring the web application? What would be the things I should look for and in which order? What about browser game versus functional web app? Would there be then difference in the approach?

答:
If it's ugly enough to piss me off, it's ugly enough for me to delete the entire thing and write a drop in replacement. </p>

<p>You'll find that more often than not, it takes the same amount of time to do this, as it does to sit there and tip-toe around an unorganized and undocumented mess and caress it gently. </p>

Body:
If it's ugly enough to piss me off, it's ugly enough for me to delete the entire thing and write a drop in replacement.

You'll find that more often than not, it takes the same amount of time to do this, as it does to sit there and tip-toe around an unorganized and undocumented mess and caress it gently.


问:
Is relying on Demorgan's law in open-source code a barrier to contribution?
I recently added this code to a Github project I'm working on:

```<code>    if not initial_push=='y' and not initial_push=='yes':
        print('Aborting.')
        return False
</code>```

Since this is a public repository that I'm hoping people will contribute to, I am considering refactoring that bit as the slightly more readable code:

```<code>    if initial_push=='y' or initial_push=='yes':
        pass
    else:
        print('Aborting.')
        return False
</code>```

If my goal is to keep the open-source project accessible to outside contribution then should I use the more readable but clumsy second method? I am actually interested in the answer for the general case, not just this specific example.

答:
Let's invert the logic here, to keep in the spirit of Demorgan's law:

Would you want "programmers"  to contribute to your project even though they have problems with elementary logic? Is that a net benefit to you? Or will they be time wastes? Does your project have enough volunteers to review their code?


答:
I don't think either of those two is really more complex or more difficult than he other. I'd choose the one without the unnecessary pass branch, because that's an unnecessary branch.

If you consider all the things that keep people from contributing to Open Source (it needs time, some programming ability, motivation, getting a Github account, making sense of the organization of a whole program, getting over the fear of not being good enough to contribute, actually creating a decent pull request, et cetera), I can't imagine that the choice of how to spell an if statement like this is ever going to make the difference between somebody contributing or not.

But in general, readable and clumsy don't usually go together. Almost always, the way that is more readable is also the less clumsy way, and the clumsy way takes more lines, more unnecessary cruft and is therefore less readable.

So: always go for maximum readability.

Title: Is relying on Demorgan's law in open-source code a barrier to contribution?

Body:
I recently added this code to a Github project I'm working on:

```<code>    if not initial_push=='y' and not initial_push=='yes':
        print('Aborting.')
        return False
</code>```

Since this is a public repository that I'm hoping people will contribute to, I am considering refactoring that bit as the slightly more readable code:

```<code>    if initial_push=='y' or initial_push=='yes':
        pass
    else:
        print('Aborting.')
        return False
</code>```

If my goal is to keep the open-source project accessible to outside contribution then should I use the more readable but clumsy second method? I am actually interested in the answer for the general case, not just this specific example.


问:
How to respond to a rude bug report?
I just received a quite rude bug report. The user basically says that we're doing it all wrong using capital letters here and there, although he's in fact just pointing at one bug.

On one hand, I care a lot about our users and want to maintain a good relationship and a good rating of our app. On the other I'd feel like a complete sell out if I would reply overly polite.

What's a decent way of responding? What should I keep in mind? What mindset should I have?

It should be added that the user seems to be a 24 year old CS student, and our product is an Android app that we're giving away free of charge.

答:
Its already the highest voted comment but I think it deserves an answer

Like this bug report: [PYTHON-532] User-triggerable NULL pointer dereference due to utter plebbery

When a user responds in this way its always out of frustration. By dealing with their issue quickly and politely you can often turn an angry customer into a fan. My favourite comment from that bug report:

Person who raised the bug:

  Apologies to anyone offended by this report. Thanks for your effort!

In summary:

Be polite and thank them for the bug report

Deal with the issue as quickly as you can

Title: How to respond to a rude bug report?


问:
Changing method signature for implementing classes in PHP
Is there any decent work around to PHP's lack of Generics that allow static code inspection to detect type consistency?

I have an abstract class, that I want to sub-class and also enforce that one of the methods changes from taking a parameter of one type, to taking a parameter which is a sub-class of that parameter.

abstract class AbstractProcessor {
    abstract function processItem(Item $item);
}

class WoodProcessor extends AbstractProcessor {
    function processItem(WoodItem $item){}
}
```

<p>This is not allowed in PHP because it's changing the methods signature which is not allowed. With Java style generics you could do something like:</p>

<pre class="lang-java prettyprint-override"><code>abstract class AbstractProcessor<T> {
    abstract function processItem(T $item);
}

class WoodProcessor extends AbstractProcessor<WoodItem> {
    function processItem(WoodItem $item);
}
</code>```

But obviously PHP doesn't support those.

Google for this problem, people suggest using instanceof to check errors at run-time e.g.

class WoodProcessor extends AbstractProcessor {
    function processItem(Item $item){
        if (!($item instanceof WoodItem)) {
            throw new \InvalidArgumentException(
                "item of class ".get_class($item)." is not a WoodItem");
        }
    }
}
```

<p>But that only works at runtime, it doesn't allow you to inspect your code for errors using static analysis - so is there any sensible way of handling this in PHP?</p>

<p>A more complete example of the problem is:</p>

<pre class="lang-php prettyprint-override"><code>class StoneItem extends Item{}
class WoodItem extends Item{}

class WoodProcessedItem extends ProcessedItem {
    function __construct(WoodItem $woodItem){}
}

class StoneProcessedItem extends ProcessedItem{
    function __construct(StoneItem $stoneItem){}
}

abstract class AbstractProcessor {
    abstract function processItem(Item $item);

    function processAndBoxItem(Box $box, Item $item) {
       $processedItem = $this->processItem($item);
       $box->insertItem($item);
    }

    //Lots of other functions that can call processItem
}

class WoodProcessor extends AbstractProcessor {
    function processItem(Item $item) {
        return new ProcessedWoodItem($item); //This has an inspection error
    }
}

class StoneProcessor extends AbstractProcessor {
    function processItem(Item $item) {
        return new ProcessedStoneItem($item);//This has an inspection error
    }
}
</code>```

Because I'm passing in just an Item to new ProcessedWoodItem($item) and it expects a WoodItem as the parameter, the code inspection suggests there is an error.

答:
You can use methods with no arguments, documenting the parameters with doc-blocks instead:

<?php

class Foo
{
    /**
     * @param string $world
     */
    public function hello()
    {
        list($world) = func_get_args();

        echo "Hello, {$world}\n";
    }
}

class Bar extends Foo
{
    /**
     * @param string $greeting
     * @param string $world
     */
    public function hello()
    {
        list($greeting, $world) = func_get_args();

        echo "{$greeting}, {$world}\n";
    }
}

$foo = new Foo();
$foo->hello('World');

$bar = new Bar();
$bar->hello('Bonjour', 'World');
```

<p>I'm not going to say I think this is a good idea though.</p>

<p>Your problem is, you have a context with a variable number of members - rather than trying to force those through as arguments, a better and more future-proof idea is to introduce a context-type to carry all possible arguments, so that the argument list never needs to change.</p>

<p>Like so:</p>

<pre class="lang-php prettyprint-override"><code><?php

class HelloContext
{
    /** @var string */
    public $greeting;

    /** @var string */
    public $world;

    public static function create($world)
    {
        $context = new self;

        $context->world = $world;

        return $context;
    }

    public static function createWithGreeting($greeting, $world)
    {
        $context = new self;

        $context->greeting = $greeting;
        $context->world = $world;

        return $context;
    }
}

class Foo
{
    public function hello(HelloContext $context)
    {
        echo "Hello, {$context->world}\n";
    }
}

class Bar extends Foo
{
    public function hello(HelloContext $context)
    {
        echo "{$context->greeting}, {$context->world}\n";
    }
}

$foo = new Foo();
$foo->hello(HelloContext::create('World'));

$bar = new Bar();
$bar->hello(HelloContext::createWithGreeting('Bonjour', 'World'));
</code>```

Static factory methods are optional of course - but could be useful, if only certain specific combinations of members produce a meaningful context. If so, you may wish to declare __construct() as protected/private as well.

Body:
You can use methods with no arguments, documenting the parameters with doc-blocks instead:

<?php

class Foo
{
    /**
     * @param string $world
     */
    public function hello()
    {
        list($world) = func_get_args();

        echo "Hello, {$world}\n";
    }
}

class Bar extends Foo
{
    /**
     * @param string $greeting
     * @param string $world
     */
    public function hello()
    {
        list($greeting, $world) = func_get_args();

        echo "{$greeting}, {$world}\n";
    }
}

$foo = new Foo();
$foo->hello('World');

$bar = new Bar();
$bar->hello('Bonjour', 'World');

I'm not going to say I think this is a good idea though.

Your problem is, you have a context with a variable number of members - rather than trying to force those through as arguments, a better and more future-proof idea is to introduce a context-type to carry all possible arguments, so that the argument list never needs to change.

Like so:

<?php

class HelloContext
{
    /** @var string */
    public $greeting;

    /** @var string */
    public $world;

    public static function create($world)
    {
        $context = new self;

        $context->world = $world;

        return $context;
    }

    public static function createWithGreeting($greeting, $world)
    {
        $context = new self;

        $context->greeting = $greeting;
        $context->world = $world;

        return $context;
    }
}

class Foo
{
    public function hello(HelloContext $context)
    {
        echo "Hello, {$context->world}\n";
    }
}

class Bar extends Foo
{
    public function hello(HelloContext $context)
    {
        echo "{$context->greeting}, {$context->world}\n";
    }
}

$foo = new Foo();
$foo->hello(HelloContext::create('World'));

$bar = new Bar();
$bar->hello(HelloContext::createWithGreeting('Bonjour', 'World'));

Static factory methods are optional of course - but could be useful, if only certain specific combinations of members produce a meaningful context. If so, you may wish to declare __construct() as protected/private as well.