问:
Unit Testing with massive lookup tables?
Our system is structured in such a way that we get a lot of key info for our calculations and other such logic from lookup type tables. Examples would be all kinds of different rates (like interest rates or contribution rates), dates (like effective dates), and all of kinds of different misc info.

Why did they decide to structure everything like this? Because some of this info changes quite often. For example some of our rates changes yearly. They wanted to try to minimize code changes. The hope was just that the lookup tables would change and the code would just work (no code changes).

Unfortunately, I think its going to make unit testing challenging. Some of the logic might make 100+ different lookups. While i can definitely make a mockable object that returns our rates there is going to be considerable setup. I think its either that or i have to end up using integration tests (and hitting that database). Am i right or is there a better way? Any suggestions?

Edit:

Sorry for the delayed response but i was trying to soak everything in while at the same thing juggling many other things. I also wanted to try to work through the implementation and at the same time. I tried a variety of patterns to try to architect the solution to something i was happy with. I tried the visitor pattern which i wasn't happy with. In the end i ended up using the onion architecture. Was i happy with the results? Sort of. I think it is what it is. The lookup tables make it a lot more challenging.

Here is a small example (im using fakeiteasy) of setup code for the tests for a rate that changes yearly:

```<code>private void CreateStubsForCrsOS39Int()
{
    CreateMacIntStub(0, 1.00000m);
    CreateMacIntStub(1, 1.03000m);
    CreateMacIntStub(2, 1.06090m);
    CreateMacIntStub(3, 1.09273m);
    CreateMacIntStub(4, 1.12551m);
    CreateMacIntStub(5, 1.15928m);
    CreateMacIntStub(6, 1.19406m);
    CreateMacIntStub(7, 1.22988m);
    CreateMacIntStub(8, 1.26678m);
    CreateMacIntStub(9, 1.30478m);
    CreateMacIntStub(10, 1.34392m);
    CreateMacIntStub(11, 1.38424m);
    CreateMacIntStub(12, 1.42577m);
    CreateMacIntStub(13, 1.46854m);
    CreateMacIntStub(14, 1.51260m);
    CreateMacIntStub(15, 1.55798m);
    CreateMacIntStub(16, 1.60472m);
    CreateMacIntStub(17, 1.65286m);
    CreateMacIntStub(18, 1.70245m);
    CreateMacIntStub(19, 1.75352m);
    CreateMacIntStub(20, 1.80613m);
    CreateMacIntStub(21, 1.86031m);
    CreateMacIntStub(22, 1.91612m);
    CreateMacIntStub(23, 1.97360m);
    CreateMacIntStub(24, 2.03281m);
    CreateMacIntStub(25, 2.09379m);
    CreateMacIntStub(26, 2.15660m);
    CreateMacIntStub(27, 2.24286m);
    CreateMacIntStub(28, 2.28794m);
    CreateMacIntStub(29, 2.35658m);
    CreateMacIntStub(30, 2.42728m);
    CreateMacIntStub(31, 2.50010m);
    CreateMacIntStub(32, 2.57510m);
    CreateMacIntStub(33, 2.67810m);
    CreateMacIntStub(34, 2.78522m);
    CreateMacIntStub(35, 2.89663m);
    CreateMacIntStub(36, 3.01250m);
    CreateMacIntStub(37, 3.13300m);
    CreateMacIntStub(38, 3.25832m);
    CreateMacIntStub(39, 3.42124m);
    CreateMacIntStub(40, 3.59230m);
    CreateMacIntStub(41, 3.77192m);
    CreateMacIntStub(42, 3.96052m);
    CreateMacIntStub(43, 4.19815m);
    CreateMacIntStub(44, 4.45004m);
    CreateMacIntStub(45, 4.71704m);
    CreateMacIntStub(46, 5.00006m);
    CreateMacIntStub(47, 5.30006m);
    CreateMacIntStub(48, 5.61806m);
    CreateMacIntStub(49, 5.95514m);
    CreateMacIntStub(50, 6.31245m);
    CreateMacIntStub(51, 6.69120m);
    CreateMacIntStub(52, 7.09267m);
    CreateMacIntStub(53, 7.51823m);
    CreateMacIntStub(54, 7.96932m);
    CreateMacIntStub(55, 8.44748m);
    CreateMacIntStub(56, 8.95433m);
    CreateMacIntStub(57, 9.49159m);
    CreateMacIntStub(58, 10.06109m);
    CreateMacIntStub(59, 10.66476m);
    CreateMacIntStub(60, 11.30465m);
    CreateMacIntStub(61, 11.98293m);
    CreateMacIntStub(62, 12.70191m);
    CreateMacIntStub(63, 13.46402m);
    CreateMacIntStub(64, 14.27186m);
    CreateMacIntStub(65, 15.12817m);
    CreateMacIntStub(66, 16.03586m);
    CreateMacIntStub(67, 16.99801m);
    CreateMacIntStub(68, 18.01789m);
    CreateMacIntStub(69, 19.09896m);
    CreateMacIntStub(70, 20.24490m);
    CreateMacIntStub(71, 21.45959m);
    CreateMacIntStub(72, 22.74717m);
    CreateMacIntStub(73, 24.11200m);
    CreateMacIntStub(74, 25.55872m);
    CreateMacIntStub(75, 27.09224m);
    CreateMacIntStub(76, 28.71778m);

}

private void CreateMacIntStub(byte numberOfYears, decimal returnValue)
{
    A.CallTo(() => _macRateRepository.GetMacArIntFactor(numberOfYears)).Returns(returnValue);
}
</code>```

Here is some setup code for a rate that can change at any point (it might be years before a new interest rate is introduced):

```<code>private void CreateStubForGenMbrRateTable()
{
    _rate = A.Fake<IRate>();
    A.CallTo(() => _rate.GetRateFigure(17, A<System.DateTime>.That.Matches(x => x < new System.DateTime(1971, 7, 1)))).Returns(1.030000000m);

    A.CallTo(() => _rate.GetRateFigure(17,
        A<System.DateTime>.That.Matches(x => x < new System.DateTime(1977, 7, 1) && x >= new System.DateTime(1971,7,1)))).Returns(1.040000000m);

    A.CallTo(() => _rate.GetRateFigure(17,
        A<System.DateTime>.That.Matches(x => x < new System.DateTime(1981, 7, 1) && x >= new System.DateTime(1971, 7, 1)))).Returns(1.050000000m);
    A.CallTo(
        () => _rate.GetRateFigure(17, A<System.DateTime>.That.IsGreaterThan(new System.DateTime(1981, 6, 30).AddHours(23)))).Returns(1.060000000m);
}
</code>```

Here is the constructor for one of my Domain Objects:

```<code>public abstract class OsEarnDetail: IOsCalcableDetail
{
    private readonly OsEarnDetailPoco _data;
    private readonly IOsMacRateRepository _macRates;
    private readonly IRate _rate;
    private const int RdRate = (int) TRSEnums.RateTypeConstants.ertRD;

    public OsEarnDetail(IOsMacRateRepository macRates,IRate rate, OsEarnDetailPoco data)
    {
        _macRates = macRates;
        _rate = rate;
        _data = data;
    }
</code>```

So why don't i like it? Well existing tests will work but anyone adding any new test in the future will have to look through this setup code to make sure any new rates are added. I tried to make it as clear as possible by using the table name as part of the function name but i guess it is what it is :)

答:
The fact that:

Some of the logic might make 100+ different lookups.

is irrelevant in a context of unit testing. A unit tests focuses on a small part of the code, usually a method, and it is unlikely that a single method needs 100+ lookup tables (if it does, refactoring should be your top concern; testing comes after that). Unless you mean 100+ lookups in a loop to the same table, in which case, you're fine.

The complexity of adding stubs and mocks for those lookups shouldn't bother you either at a scale of a single unit test. Within the test, you will stub/mock only those of the lookups which are actually in use by the method. Not only won't you have a lot of them, but also those stubs or mocks will be very simple. For instance, they may return a single value, no matter what the method is looking for (as if an actual lookup was filled with the same number).

When the complexity will matter is when you'll have to test the business logic. 100+ lookups probably means thousands and thousands of different business cases to test (even outside lookups), which means thousands and thousands of unit tests.

Illustration

For example, in a context of an OLAP cube, you may have a method which relies on two cubes, one with two dimensions and one with five dimensions:

public class HelloWorld
{
    // Intentionally hardcoded cubes.
    private readonly OlapCube olapVersions = new VersionsOlapCube();
    private readonly OlapCube olapStatistics = new StatisticsOlapCube();

    ...

    public int Demo(...)
    {
        ...
        this.olapVersions.Find(a, b);
        ...
        this.olapStatistics.Find(c, d, 0, e, 0);
        ...
    }
}
```

<p>As is, the method cannot be unit tested. The first step is to make it possible to replace OLAP cubes by stubs. One way to do it is through Dependency Injection.</p>

<pre class="lang-cs prettyprint-override"><code>public class HelloWorld
{
    // Notice the interface instead of a class.
    private readonly IOlapCube olapVersions;
    private readonly IOlapCube olapStatistics;

    // Constructor.
    public HelloWorld(
        IVersionsOlapCube olapVersions, IStatisticsOlapCube olapStatistics)
    {
    }

    ...

    public void Demo(...)
    {
        ...
        this.olapVersions.Find(a, b);
        ...
        this.olapStatistics.Find(c, d, 0, e, 0);
        ...
    }
}
</code>```

Now a unit test can inject a stub like this:

class OlapCubeStub : IOlapCube
{
    public OlapValue Find(params int[] values)
    {
        return OlapValue.FromInt(1); // Constant value here.
    }
}
```

<p>and used like that:</p>

<pre class="lang-cs prettyprint-override"><code>var helloWorld = new HelloWorld(new OlapCubeStub(), new OlapCubeStub());
var actual = helloWorld.Demo();
var expected = 9;
this.AssertEquals(expected, actual);
</code>```

Body:
The fact that:

Some of the logic might make 100+ different lookups.

is irrelevant in a context of unit testing. A unit tests focuses on a small part of the code, usually a method, and it is unlikely that a single method needs 100+ lookup tables (if it does, refactoring should be your top concern; testing comes after that). Unless you mean 100+ lookups in a loop to the same table, in which case, you're fine.

The complexity of adding stubs and mocks for those lookups shouldn't bother you either at a scale of a single unit test. Within the test, you will stub/mock only those of the lookups which are actually in use by the method. Not only won't you have a lot of them, but also those stubs or mocks will be very simple. For instance, they may return a single value, no matter what the method is looking for (as if an actual lookup was filled with the same number).

When the complexity will matter is when you'll have to test the business logic. 100+ lookups probably means thousands and thousands of different business cases to test (even outside lookups), which means thousands and thousands of unit tests.

Illustration

For example, in a context of an OLAP cube, you may have a method which relies on two cubes, one with two dimensions and one with five dimensions:

public class HelloWorld
{
    // Intentionally hardcoded cubes.
    private readonly OlapCube olapVersions = new VersionsOlapCube();
    private readonly OlapCube olapStatistics = new StatisticsOlapCube();

    ...

    public int Demo(...)
    {
        ...
        this.olapVersions.Find(a, b);
        ...
        this.olapStatistics.Find(c, d, 0, e, 0);
        ...
    }
}

As is, the method cannot be unit tested. The first step is to make it possible to replace OLAP cubes by stubs. One way to do it is through Dependency Injection.

public class HelloWorld
{
    // Notice the interface instead of a class.
    private readonly IOlapCube olapVersions;
    private readonly IOlapCube olapStatistics;

    // Constructor.
    public HelloWorld(
        IVersionsOlapCube olapVersions, IStatisticsOlapCube olapStatistics)
    {
    }

    ...

    public void Demo(...)
    {
        ...
        this.olapVersions.Find(a, b);
        ...
        this.olapStatistics.Find(c, d, 0, e, 0);
        ...
    }
}

Now a unit test can inject a stub like this:

class OlapCubeStub : IOlapCube
{
    public OlapValue Find(params int[] values)
    {
        return OlapValue.FromInt(1); // Constant value here.
    }
}

and used like that:

var helloWorld = new HelloWorld(new OlapCubeStub(), new OlapCubeStub());
var actual = helloWorld.Demo();
var expected = 9;
this.AssertEquals(expected, actual);


答:
You can still write unit tests. What your question describes is a scenario in which you have some data sources that your code depends on. These data sources need to produce the same fake data across all of your tests. However, you don't want the clutter associated with setting up responses for every single test. What you need are test fakes

A test fake is an implementation of something that looks like a duck and quacks like a duck, but doesn't do anything but provide consistent responses for the purposes of testing.

In your case, you may have an IExchangeRateLookup interface and a production implementation of it

```<code>public interface IExchangeRateLookup
{
    float Find(Currency currency);
}

public class DatabaseExchangeRateLookup : IExchangeRateLookup
{
    public float Find(Currency currency)
    {
        return SomethingFromTheDatabase(currency);
    }
}
</code>```

By depending on the interface in the code under test, you're able to pass in anything which implements it, including a fake

```<code>public class ExchangeRateLookupFake : IExchangeRateLookup
{
    private Dictionary<Currency, float> _lookup = new Dictionary<Currency, float>();

    public ExchangeRateLookupFake()
    {
        _lookup = IntialiseLookupWithFakeValues();
    }

    public float Find(Currency currency)
    {
        return _lookup[currency];
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Unit Testing with massive lookup tables?

Body:
Our system is structured in such a way that we get a lot of key info for our calculations and other such logic from lookup type tables. Examples would be all kinds of different rates (like interest rates or contribution rates), dates (like effective dates), and all of kinds of different misc info.

Why did they decide to structure everything like this? Because some of this info changes quite often. For example some of our rates changes yearly. They wanted to try to minimize code changes. The hope was just that the lookup tables would change and the code would just work (no code changes).

Unfortunately, I think its going to make unit testing challenging. Some of the logic might make 100+ different lookups. While i can definitely make a mockable object that returns our rates there is going to be considerable setup. I think its either that or i have to end up using integration tests (and hitting that database). Am i right or is there a better way? Any suggestions?

Edit:

Sorry for the delayed response but i was trying to soak everything in while at the same thing juggling many other things. I also wanted to try to work through the implementation and at the same time. I tried a variety of patterns to try to architect the solution to something i was happy with. I tried the visitor pattern which i wasn't happy with. In the end i ended up using the onion architecture. Was i happy with the results? Sort of. I think it is what it is. The lookup tables make it a lot more challenging.

Here is a small example (im using fakeiteasy) of setup code for the tests for a rate that changes yearly:

```<code>private void CreateStubsForCrsOS39Int()
{
    CreateMacIntStub(0, 1.00000m);
    CreateMacIntStub(1, 1.03000m);
    CreateMacIntStub(2, 1.06090m);
    CreateMacIntStub(3, 1.09273m);
    CreateMacIntStub(4, 1.12551m);
    CreateMacIntStub(5, 1.15928m);
    CreateMacIntStub(6, 1.19406m);
    CreateMacIntStub(7, 1.22988m);
    CreateMacIntStub(8, 1.26678m);
    CreateMacIntStub(9, 1.30478m);
    CreateMacIntStub(10, 1.34392m);
    CreateMacIntStub(11, 1.38424m);
    CreateMacIntStub(12, 1.42577m);
    CreateMacIntStub(13, 1.46854m);
    CreateMacIntStub(14, 1.51260m);
    CreateMacIntStub(15, 1.55798m);
    CreateMacIntStub(16, 1.60472m);
    CreateMacIntStub(17, 1.65286m);
    CreateMacIntStub(18, 1.70245m);
    CreateMacIntStub(19, 1.75352m);
    CreateMacIntStub(20, 1.80613m);
    CreateMacIntStub(21, 1.86031m);
    CreateMacIntStub(22, 1.91612m);
    CreateMacIntStub(23, 1.97360m);
    CreateMacIntStub(24, 2.03281m);
    CreateMacIntStub(25, 2.09379m);
    CreateMacIntStub(26, 2.15660m);
    CreateMacIntStub(27, 2.24286m);
    CreateMacIntStub(28, 2.28794m);
    CreateMacIntStub(29, 2.35658m);
    CreateMacIntStub(30, 2.42728m);
    CreateMacIntStub(31, 2.50010m);
    CreateMacIntStub(32, 2.57510m);
    CreateMacIntStub(33, 2.67810m);
    CreateMacIntStub(34, 2.78522m);
    CreateMacIntStub(35, 2.89663m);
    CreateMacIntStub(36, 3.01250m);
    CreateMacIntStub(37, 3.13300m);
    CreateMacIntStub(38, 3.25832m);
    CreateMacIntStub(39, 3.42124m);
    CreateMacIntStub(40, 3.59230m);
    CreateMacIntStub(41, 3.77192m);
    CreateMacIntStub(42, 3.96052m);
    CreateMacIntStub(43, 4.19815m);
    CreateMacIntStub(44, 4.45004m);
    CreateMacIntStub(45, 4.71704m);
    CreateMacIntStub(46, 5.00006m);
    CreateMacIntStub(47, 5.30006m);
    CreateMacIntStub(48, 5.61806m);
    CreateMacIntStub(49, 5.95514m);
    CreateMacIntStub(50, 6.31245m);
    CreateMacIntStub(51, 6.69120m);
    CreateMacIntStub(52, 7.09267m);
    CreateMacIntStub(53, 7.51823m);
    CreateMacIntStub(54, 7.96932m);
    CreateMacIntStub(55, 8.44748m);
    CreateMacIntStub(56, 8.95433m);
    CreateMacIntStub(57, 9.49159m);
    CreateMacIntStub(58, 10.06109m);
    CreateMacIntStub(59, 10.66476m);
    CreateMacIntStub(60, 11.30465m);
    CreateMacIntStub(61, 11.98293m);
    CreateMacIntStub(62, 12.70191m);
    CreateMacIntStub(63, 13.46402m);
    CreateMacIntStub(64, 14.27186m);
    CreateMacIntStub(65, 15.12817m);
    CreateMacIntStub(66, 16.03586m);
    CreateMacIntStub(67, 16.99801m);
    CreateMacIntStub(68, 18.01789m);
    CreateMacIntStub(69, 19.09896m);
    CreateMacIntStub(70, 20.24490m);
    CreateMacIntStub(71, 21.45959m);
    CreateMacIntStub(72, 22.74717m);
    CreateMacIntStub(73, 24.11200m);
    CreateMacIntStub(74, 25.55872m);
    CreateMacIntStub(75, 27.09224m);
    CreateMacIntStub(76, 28.71778m);

}

private void CreateMacIntStub(byte numberOfYears, decimal returnValue)
{
    A.CallTo(() => _macRateRepository.GetMacArIntFactor(numberOfYears)).Returns(returnValue);
}
</code>```

Here is some setup code for a rate that can change at any point (it might be years before a new interest rate is introduced):

```<code>private void CreateStubForGenMbrRateTable()
{
    _rate = A.Fake<IRate>();
    A.CallTo(() => _rate.GetRateFigure(17, A<System.DateTime>.That.Matches(x => x < new System.DateTime(1971, 7, 1)))).Returns(1.030000000m);

    A.CallTo(() => _rate.GetRateFigure(17,
        A<System.DateTime>.That.Matches(x => x < new System.DateTime(1977, 7, 1) && x >= new System.DateTime(1971,7,1)))).Returns(1.040000000m);

    A.CallTo(() => _rate.GetRateFigure(17,
        A<System.DateTime>.That.Matches(x => x < new System.DateTime(1981, 7, 1) && x >= new System.DateTime(1971, 7, 1)))).Returns(1.050000000m);
    A.CallTo(
        () => _rate.GetRateFigure(17, A<System.DateTime>.That.IsGreaterThan(new System.DateTime(1981, 6, 30).AddHours(23)))).Returns(1.060000000m);
}
</code>```

Here is the constructor for one of my Domain Objects:

```<code>public abstract class OsEarnDetail: IOsCalcableDetail
{
    private readonly OsEarnDetailPoco _data;
    private readonly IOsMacRateRepository _macRates;
    private readonly IRate _rate;
    private const int RdRate = (int) TRSEnums.RateTypeConstants.ertRD;

    public OsEarnDetail(IOsMacRateRepository macRates,IRate rate, OsEarnDetailPoco data)
    {
        _macRates = macRates;
        _rate = rate;
        _data = data;
    }
</code>```

So why don't i like it? Well existing tests will work but anyone adding any new test in the future will have to look through this setup code to make sure any new rates are added. I tried to make it as clear as possible by using the table name as part of the function name but i guess it is what it is :)

Body:
You can still write unit tests. What your question describes is a scenario in which you have some data sources that your code depends on. These data sources need to produce the same fake data across all of your tests. However, you don't want the clutter associated with setting up responses for every single test. What you need are test fakes

A test fake is an implementation of something that looks like a duck and quacks like a duck, but doesn't do anything but provide consistent responses for the purposes of testing.

In your case, you may have an IExchangeRateLookup interface and a production implementation of it

public interface IExchangeRateLookup
{
    float Find(Currency currency);
}

public class DatabaseExchangeRateLookup : IExchangeRateLookup
{
    public float Find(Currency currency)
    {
        return SomethingFromTheDatabase(currency);
    }
}

By depending on the interface in the code under test, you're able to pass in anything which implements it, including a fake

public class ExchangeRateLookupFake : IExchangeRateLookup
{
    private Dictionary<Currency, float> _lookup = new Dictionary<Currency, float>();

    public ExchangeRateLookupFake()
    {
        _lookup = IntialiseLookupWithFakeValues();
    }

    public float Find(Currency currency)
    {
        return _lookup[currency];
    }
}


问:
Merits of Namepsaces/Packages
Some programming languages (e.g. Java and C++) have language features called "packages" or "namespaces".  How useful is it really to have namespaces?  It is possible to mark functions and classes as belonging to some particular library without using such a language feature, like the SDL does (e.g. SDL_BlitSurface()).  Are namespaces not helpful enough to be worth having?  Are they useful in libraries but not in applications?  Are they useful everywhere except for in small projects?  Thoughts?

答:
Namespaces/Modules/Packages are useful for avoiding name conflicts. So is name prefixing but namespaces have the added convenience of being able to import symbols into the current namespace so that you don't have to bother with the whole Namespace::*.

Some languages (like Python) extend this ability by allowing you to import only specific symbols into your current module or import symbols as a different name. This is useful if you are only interested in a few classes/functions/constants or if some of the symbols conflict with symbols in your namespace but some don't.

Some languages (like Ruby) allow you to include the methods of a module into your class. This is useful for polymorphism and generics. For example, if you have several classes that have iterators that act in the same way, you can mix methods in to all of these classes from a separate module that provides methods to sort and filter the data in the object. This allows has a relationships as well as is a (inheritance) relationships .

ContentLicense: CC BY-SA 2.5

Title: Merits of Namepsaces/Packages


问:
Repeating Interface inheritance declarations
Take the following example:

```<code>public interface ISerialRVD
{
    RouteValueDictionary ToRVD();
}

public interface IViewModel : ISerialRVD // Here?
{
    Int32 Page { get; set; }
    String Action { get; set; }
}

public class myViewModel : IViewModel, ISerialRVD // Or Here?
{

}
</code>```

I understand that if I make IViewModel inherit ISerialRVD that is forcing all who implement IViewModel to implement ISerialRVD but should I do just : IViewModel or : IViewModel, ISerialRVD on the class implementing IViewModel?

To my knowledge repeating the ISerialRVD part does not hurt anything, and I want to put it there to make it clearer it's implementing that interface, but if I were to have many more interfaces it would become quite the clutter. Am I wrong?

Is there a sensible way of dealing with this? On one-hand I feel it should be verbose and tell you what you're implementing, but on the other hand it should be infer-able from the interface itself. All IViewModels implement ISerialRVD.

答:
Imagine the following cases:

interface IReadable { }

interface IWriteable extends IReadable { }

class MemoryStream implements IWriteable { }
```

<p>By looking at the signature of <code>MemoryStream</code> only, is it obvious that the stream can be read? Probably not: you may believe that the stream is write-only, unless you know that in that specific business logic, you can always read from a writeable stream.</p>

<p>Thus, declaring both interfaces improves readability in this case.</p>

<p>Now consider another example:</p>

<pre class="lang-java prettyprint-override"><code>interface IEquatable<T> { }

interface IComparable<T> extends IEquatable<T> { }

class Price implements IComparable<int> { }
</code>```

Here, the natural thing is to believe that an object which can numerically be compared to another (that is, determine if an object is inferior or superior to another), the object can also be compared strictly to another one (that is, determine if an object is equal to another). Indeed, the second interface extends the first one, matching the expectations.

Thus, declaring both interfaces is redundant in this case.

Body:
Imagine the following cases:

interface IReadable { }

interface IWriteable extends IReadable { }

class MemoryStream implements IWriteable { }

By looking at the signature of MemoryStream only, is it obvious that the stream can be read? Probably not: you may believe that the stream is write-only, unless you know that in that specific business logic, you can always read from a writeable stream.

Thus, declaring both interfaces improves readability in this case.

Now consider another example:

interface IEquatable<T> { }

interface IComparable<T> extends IEquatable<T> { }

class Price implements IComparable<int> { }

Here, the natural thing is to believe that an object which can numerically be compared to another (that is, determine if an object is inferior or superior to another), the object can also be compared strictly to another one (that is, determine if an object is equal to another). Indeed, the second interface extends the first one, matching the expectations.

Thus, declaring both interfaces is redundant in this case.


问:
Do I suffer from encapsulation overuse?
I have noticed something in my code in various projects that seems like code smell to me and something bad to do, but I can't deal with it.

While trying to write "clean code" I tend to over-use private methods in order to make my code easier to read. The problem is that the code is indeed cleaner but it's also more difficult to test (yeah I know I can test private methods...) and in general it seems a bad habit to me.

Here's an example of a class that reads some data from a .csv file and returns a group of customers (another object with various fields and attributes).

public class GroupOfCustomersImporter {
    //... Call fields ....
    public GroupOfCustomersImporter(String filePath) {
        this.filePath = filePath;
        customers = new HashSet<Customer>();
        createCSVReader();
        read();
        constructTTRP_Instance();
    }

    private void createCSVReader() {
        //....
    }

    private void read() {
        //.... Reades the file and initializes the class attributes
    }

    private void readFirstLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readSecondLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void readCustomerLine(String[] inputLine) {
        //.... Method used by the read() method
    }

    private void constructGroupOfCustomers() {
        //this.groupOfCustomers = new GroupOfCustomers(**attributes of the class**);
    }

    public GroupOfCustomers getConstructedGroupOfCustomers() {
        return this.GroupOfCustomers;
    }
}
```

<p>As you can see the class has only a constructor which calls some private methods to get the job done, I know that's not a good practice in general but I prefer to encapsulate all the functionality in the class instead of making the methods public in which case a client should work this way:</p>

```GroupOfCustomersImporter importer = new GroupOfCustomersImporter(filepath)
importer.createCSVReader();
read();
GroupOfCustomer group = constructGoupOfCustomerInstance();
```

I prefer this because I don't want to put useless lines of code in the client's side code bothering the client class with implementation details.

So, Is this actually a bad habit? If yes, how can I avoid it? Please note that the above is just a simple example. Imagine the same situation happening in something a little bit more complex.

答:
The constructor should not do too much except initializing some variables or the state of the object. Doing too much in constructor can raise runtime exceptions.
I would try avoiding client doing somenthing like this:

```<code>MyClass a;
try {
   a = new MyClass();
} catch (MyException e) {
   //do something
}
</code>```

Instead of doing:

```<code>MyClass a = new MyClass(); // Or a factory method
try {
   a.doSomething();
} catch (MyException e) {
   //do something
}
</code>```

Title: Do I suffer from encapsulation overuse?

Body:
The constructor should not do too much except initializing some variables or the state of the object. Doing too much in constructor can raise runtime exceptions.
I would try avoiding client doing somenthing like this:

MyClass a;
try {
   a = new MyClass();
} catch (MyException e) {
   //do something
}

Instead of doing:

MyClass a = new MyClass(); // Or a factory method
try {
   a.doSomething();
} catch (MyException e) {
   //do something
}


问:
Returning a slimmed down domain entity from your view model
I'm wondering how to handle a ViewModel in the traditional sense, which includes both properties and methods, and another "view model" which is simply just the properties -- perhaps the ViewModel would return a this view "entity", or something.

Let me explain:

Domain Model:

```<code>public class Workout
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string SomethingElse { get; set; }
    public List<Exercise> Exercises { get; set; }
    public DateTime CreatedDate { get; set; }
}
</code>```

View Model:

```<code>public class WorkoutHistoryViewModel : IWorkoutHistoryViewModel
{
    private IWorkoutRepository workoutRepository;

    public WorkoutHistoryViewModel(IWorkoutRepository workoutRepository)
    {
        this.workoutRepository = workoutRepository;
    }

    // Here I'd like to return a slimmed down entity, not the full entity
    public IEnumerable<WorkoutHistoryViewEntity> GetExistingWorkouts()
    {
        return this.workoutRepository.GetList(); // some mapping logic
    }
}
</code>```

And perhaps the desired "view entity" would just be:

```<code>public class WorkoutHistoryViewEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

I will also need to do something similar for, say, a WorkoutDetailsViewModel, which will require a different set of properties for its "view model", like:

```<code>public class WorkoutDetailsViewEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Exercise> Exercises { get; set; }
}
</code>```

So, I guess the questions are:

Am I doing MVVM all wrong?  Should this ViewModel also have the desired properties on it?  If so, then, when I do a GetExistingWorkouts(), am I really supposed to return a List<WorkoutHistoryViewModel>?  In that case, I'd have a bunch of objects, all with repositories and methods, when really I just want the data.

If I should create a third class, like the WorkoutHistoryViewEntity, what are these typically called (as ViewEntity doesn't really sound right).

答:
You needn't worry about your ViewModels having more functionality than just providing data. That is, after all, their true function - to provide the data for display and any functionality required by the View. ViewModel's will normally contain properties, ICommands, at least one model and any references to services and repositories required to deal with modifications to the model.

In your case, your WorkoutHistoryViewModel will provide an ObservableCollection<WorkoutViewModel>, each of which has a Workout object as it's model.

so to answer your 2 questions:

You're doing MVVM just fine. Don't worry about it seeming a little verbose - there's reasons for the separation. And almost all viewmodels will have some references to services as well as data.

Don't create a "ViewEntity". Just create a ViewModel.


答:
Returning a List<WorkoutHistoryViewModel> feels not as the way to go for me, even though it's done often. Your second option is better, and I think you got this quite right by intuition.

You are right though that WorkhoutHistoryViewEntity is not an appropriate name. It could mean almost anything. It's hard to find a name for the Id and the name because the first one is technical and the second one isn't. I assume here that the Id is unique and the name isn't. In this case, is there probably a way to either return only a list of names or a list of Ids? This could solve your problem, because I wonder if there is a good reason to return both information together. If there is a good reason, telling us might make it more easy to find a good name. Else you can also go with WorkoutIdAndName.

If both Id and name are unique, go with WorkoutReference or WorkoutIdentifier (and also use this class internal to store Id and an alias (here it would be the name)).

Title: Returning a slimmed down domain entity from your view model

Body:
I'm wondering how to handle a ViewModel in the traditional sense, which includes both properties and methods, and another "view model" which is simply just the properties -- perhaps the ViewModel would return a this view "entity", or something.

Let me explain:

Domain Model:

```<code>public class Workout
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string SomethingElse { get; set; }
    public List<Exercise> Exercises { get; set; }
    public DateTime CreatedDate { get; set; }
}
</code>```

View Model:

```<code>public class WorkoutHistoryViewModel : IWorkoutHistoryViewModel
{
    private IWorkoutRepository workoutRepository;

    public WorkoutHistoryViewModel(IWorkoutRepository workoutRepository)
    {
        this.workoutRepository = workoutRepository;
    }

    // Here I'd like to return a slimmed down entity, not the full entity
    public IEnumerable<WorkoutHistoryViewEntity> GetExistingWorkouts()
    {
        return this.workoutRepository.GetList(); // some mapping logic
    }
}
</code>```

And perhaps the desired "view entity" would just be:

```<code>public class WorkoutHistoryViewEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
}
</code>```

I will also need to do something similar for, say, a WorkoutDetailsViewModel, which will require a different set of properties for its "view model", like:

```<code>public class WorkoutDetailsViewEntity
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Exercise> Exercises { get; set; }
}
</code>```

So, I guess the questions are:

Am I doing MVVM all wrong?  Should this ViewModel also have the desired properties on it?  If so, then, when I do a GetExistingWorkouts(), am I really supposed to return a List<WorkoutHistoryViewModel>?  In that case, I'd have a bunch of objects, all with repositories and methods, when really I just want the data.

If I should create a third class, like the WorkoutHistoryViewEntity, what are these typically called (as ViewEntity doesn't really sound right).


问:
Is the git "Golden Rule of Rebasing" so essential?
I had a discussion recently with people absolutely opposed to a rebase strategy of feature branches on GIT. It seems to be an accepted pattern to use rebase only for local, private branches but never use it when there's several people working on a same feature & branch, as per this so-called "Golden Rule of Rebasing" (like explained here: https://www.atlassian.com/git/tutorials/merging-vs-rebasing/conceptual-overview )

I am just surprised there's a consensus on this. I worked 3 years with a full rebasing strategy, with about 20 developers working togeteher and guess what, it worked.

The process is basically:

You create your feature branch, let's call it "myfeature", and push it to origin/myfeature

Other people may check it out and work on it

You may sometimes rebase it from master: from "myfeature", git rebase origin/master ; and then, yes, you have to push-force it.

What happens when other people want to push their commits? They just rebase it: git rebase origin/myfeature . So they're now in fast-forward and can push it without forcing.

The only principle to respect is that the feature branch is owned by someone. The owner is the only one who can push-force.

So, I admit: as soon as there's a push-force, there's a risk to do errors. That's true. But there's also many ways to recover from errors, and really, in 3 years of development, I didn't saw a lot of force-pushing mistakes, and when it came to happen we always found a way to recover properly.

So, why is this "Golden Rule of Rebase" being so widely accepted? Is there something else I missed with that? I understand it requires a minimum of organization (every strategy requires some organization), but it works.

答:
Rebase isn't essential, as you say it is mostly cosmetic.  Sometimes it is a lot simpler then a merge.  So it can have some "actual" value, but only "sometimes"

Improper use of rebase can be costly.  Unlikely to lose data if you know enough to not panic and look up recovery procedures, but "hey nobody push for a while I have to fix ..." isn't great.  Nor is having someone burn time on research recovery and testing when they could have been adding features or squashing bugs (or home with family).

With that trade off the results of "very few people do a rebase and forced push" isn't very surprising.

Some workflows can reduce the risk, for example reduce it to "zero as long as you remember which branches you are allowed to force and which you can't".  In reality they might be safe enough to justify the risk, but folks frequently make choices based on larger folklore.  Then again in reality the benefits are pretty small, so how tiny does the risk really need to be?


问:
Design question concerning extensibility
I am constructing a new class which handles deciding which class should process the requests from a web service.  I'm looking for a solution for a problem that I am having regarding extensibility with this new class.  Each request will be processed differently, and the logic for processing them each are in their own class.  The problem that I am hoping to solve is how to design the classes in such a way that adding a new type of request does not require any changes to existing code.  Consider the code that I have below.  Please pardon any typos in the following examples:

public interface IRequestData
{

}

public class OldRequestData : IRequestData
{
    // Some properties holding data.
}

public class NewRequestData : IRequestData
{
    // Some properties holding data.
}

public class ProcessOldRequestData
{
    public void Process(OldRequestData Data)
    {
        // Some code to process the request.
    }
}

public class ProcessNewRequestData
{
    public void Process(NewRequestData Data)
    {
        // Some code to process the request.
    }
}

public class RequestProcessor
{
    public void ProcessRequest(IRequestData Data)
    {
        // Get and load base type of Data

        // Based on if it's OldRequestData, NewRequestData, or *FutureRequestData*,
        // Instantiate the appropriate class to process the request.
    }
}
```

This is the model that I am currently working with.  The problem is each new type of request requires changes to the RequestProcessor to call the new class.  Is there a way to make this class "Know" which class it needs to call to process each type of request?  If there is a better of handling this I would be very open for other suggestions.

Thank you in advance for your input.

答:
create a collection (map, dictionary, etc) of requests to objects. In ProcessRequest, you iterate through the collection to find an entry that matches the input request, and call the associated object.

Then you only have to populate the collection, but this can be done by reading configuration or by having each RequestData class register itself at startup (by adding itself to your collection along with the set of requests it can handle).

of course, if you have to create a new 'FutureRequestData' class with custom logic, then you will have to update your code. There's no getting round that unless you execute arbitrary code that is read from config (eg a scripting language) and you have some engine or compiler that can cause this code to execute.


答:
There are two ways to do it.

The OO way: Make your current OldRequestData and NewRequestData classes more active and let them implement a method that is executing the desired behaviour. This means your Process methods will be put into your IRequestData classes. The advantage is that you can now add classes implement IRequestData and let them implement have the corresponding Process methods. The drawback here kicks in as soon as you want to have differend kind of Process method for each IRequestData class (e.g. two different ways of processing OldRequestData and also two different ways of processing NewRequestData)

Solving the drawbacks of the first solution means diving into the Expression Problem (even though we use a dynamically typed language here). There are different ways to solve this, but they lead to more complexity. You have to weight the benefits against the complexity. If you don't want IRequestData classes, you should stay with the first solution.

Title: Design question concerning extensibility

Body:
I am constructing a new class which handles deciding which class should process the requests from a web service.  I'm looking for a solution for a problem that I am having regarding extensibility with this new class.  Each request will be processed differently, and the logic for processing them each are in their own class.  The problem that I am hoping to solve is how to design the classes in such a way that adding a new type of request does not require any changes to existing code.  Consider the code that I have below.  Please pardon any typos in the following examples:

public interface IRequestData
{

}

public class OldRequestData : IRequestData
{
    // Some properties holding data.
}

public class NewRequestData : IRequestData
{
    // Some properties holding data.
}

public class ProcessOldRequestData
{
    public void Process(OldRequestData Data)
    {
        // Some code to process the request.
    }
}

public class ProcessNewRequestData
{
    public void Process(NewRequestData Data)
    {
        // Some code to process the request.
    }
}

public class RequestProcessor
{
    public void ProcessRequest(IRequestData Data)
    {
        // Get and load base type of Data

        // Based on if it's OldRequestData, NewRequestData, or *FutureRequestData*,
        // Instantiate the appropriate class to process the request.
    }
}
```

This is the model that I am currently working with.  The problem is each new type of request requires changes to the RequestProcessor to call the new class.  Is there a way to make this class "Know" which class it needs to call to process each type of request?  If there is a better of handling this I would be very open for other suggestions.

Thank you in advance for your input.


答:
Look at using the Abstract factory, Builder and Factory method patterns.

These will let you do something like the below (apologies for any syntax errors):

```<code>IRequestData rd = RequestDataBuilder.Build('old').GetData();
// not strictly necessary but follow the pattern throughout
IRequestProcessor rp = RequestProcessorBuilder.Build().GetProcessor();
</code>```

on which you can now do

```<code>rp.ProcessRequest(rd);
</code>```

without knowing - or caring - about which (old or new) set of data or processor you're working on.

The RequestProcessorBuilder can figure out which request processor to build based on arguments passed in to the Build() method or some other parameters used by the builder.

So the default might be a 'fast' ProcessSpeed but we can also specify a 'slow' speed, in which case a different object is returned. Importantly, the called doesn't care, since it just interacts with an interface.

```<code>IRequestProcessor rp = RequestProcessorBuilder.Build()
                         .ProcessSpeed('slow')
                         .GetProcessor();
</code>```

Alternatively, the decision as to which object the builder returns can come from config (file, db, wherever).

From those links (which have examples), a short description:

Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes

Builder: Separate the construction of a complex object from its  representation, allowing the same construction process to create various representations

Factory method: Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses

Body:
Look at using the Abstract factory, Builder and Factory method patterns.

These will let you do something like the below (apologies for any syntax errors):

IRequestData rd = RequestDataBuilder.Build('old').GetData();
// not strictly necessary but follow the pattern throughout
IRequestProcessor rp = RequestProcessorBuilder.Build().GetProcessor();

on which you can now do

rp.ProcessRequest(rd);

without knowing - or caring - about which (old or new) set of data or processor you're working on.

The RequestProcessorBuilder can figure out which request processor to build based on arguments passed in to the Build() method or some other parameters used by the builder.

So the default might be a 'fast' ProcessSpeed but we can also specify a 'slow' speed, in which case a different object is returned. Importantly, the called doesn't care, since it just interacts with an interface.

IRequestProcessor rp = RequestProcessorBuilder.Build()
                         .ProcessSpeed('slow')
                         .GetProcessor();

Alternatively, the decision as to which object the builder returns can come from config (file, db, wherever).

From those links (which have examples), a short description:

Abstract factory: Provide an interface for creating families of related or dependent objects without specifying their concrete classes

Builder: Separate the construction of a complex object from its  representation, allowing the same construction process to create various representations

Factory method: Define an interface for creating a single object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses


问:
PHP Refactoring advice
I'm working on a Soccer management game. Project is fairly new and small and I'm new to PHP. The project was starting to get a bit messy so I've been looking into refactoring. The first thing I've done is to make my functions smaller, which helps a lot. I also added my functions to my classes, since they were originally a bunch of small functions, included in the project. The problem is, now my classes are starting to get large and I don't want to go in the wrong direction with my coding/learning.

I'm thinking of removing some of the methods into their own class but I'm not sure of how this works. For example, my Team class currently does two things (which is one too many?). Firstly it does database work (load/save/create a team) and I'm now adding functions to allow the AI to select a squad. This is already six small methods. Could I make a second class, just for this second group of methods, with no properties? If so, how would this work?

For example, say that I already have my 'Team' object. Do I create a 'Team Select' object, just to use those methods, then pass my 'Team' object into the methods, so something like teamselectobj->SelectTeam($Teamobject). Although this makes my classes smaller, it does seem like extra unnecessary steps. Is this good refactoring practice?

答:
Sounds like you are not very good just yet with the responsibility assignment in programming. Have a look at General Responsibility Assignment Software Patterns. They will tell you exactly where to place each method and property.

You want to have a class that defines an object with it's own properties and methods to act upon it. You don't want to just create a class because it would be 6 methods there because they don't belong anywhere else.

Title: PHP Refactoring advice


问:
Mobile Web App - combines with exist web app or separate them
The company I work for already has a fully functional web app that is written in java using JSF framework. I'm now in the process of creating a mobile version of this web app and having some general questions on where to put this mobile web app.

Should this mobile web app be a separate project, packaged in a different war, and installed as separate app in server or should it be part of the existing web app, packaged in the same war, and installed as same app in server?

Should the mobile web app uses existing web app's jsf Manage Beans? For example, we already have an order entry app that consists of several jsf Manage Beans and jsf pages. To create the mobile version of this app, should I simply create new mobile version of jsf pages but uses all the exist jsf Manage Beans in those mobile jsf pages? Will I run into problem because mobile web app's page-flow might be different from the web app's page-flow? But if I don't reuse, it seems like there will be a lot of duplicate code.

答:
(1) depends on the intended life cycles of your web app and the mobile version of the app. If you give both always the same version number and deploy them both always simultanously, it makes more sense to keep them in the same project. If the life cycles are somewhat different (for example, you create a new version of your mobile app every 3 months, but a new version of your web app every day), then it is better to keep them as different projects.

(2) depends on (1). If the life cycle of both is the same, it will be probably much easier to have shared components, since you can always use the same version of those components.  If the life cycle is different, reusing your "Managed Beans" is not impossible, but will probably need much more care and configuration management, so you do not run into problems when a older mobile app version accesses the same data produced with a newer version of your Web App.


问:
Algorithm to find the optimal trade route (negative cycle with lowest cost per edge in a digraph)
Given the following problem (a slightly simplified description of trading in the computer game Escape Velocity: Nova (system map)):

Given a set of (solar) systems.

Each system is connected by hyperspace travel route to one or more other systems; each route connects two systems.

Making a hyperspace jump has a cost in dollars (covering fuel costs). The cost is the same no matter which jump you're making.

Each system has a trading center with various commodities (food, metal, equipment, etc.) available for trade at a given price. The price varies between systems.

To keep it simple we'll say you can only hold a single unit of a single commodity at any given time.

A trade route is a series of hyperspace jumps that start and end in the same system (a loop), buying and selling commodities along the way.

The profit of a trade route is defined as profit made by buying and selling commodities along the way minus the total cost of the hyperspace jumps made.

I want to be able to answer questions like the following:

What's the most profitable trade route?

What's the most profitable trade route starting and ending in a specific system?

What's the most profitable trade route involving fewer than X jumps?

What's the most profitable trade route involving fewer than X jumps starting and ending in a specific system?

I plan to model this as a digraph:

Each system is a vertex.

For each hyperspace travel route add two edges (one in each direction) connecting the two vertexes with a weight equal to the cost of making a hyperspace jump.

For each system

for each commodity available in that system

for each system where the price of the commodity is lower than in the current system (we'll never make a profit if the cost at the destination is higher so we omit those edges)

add an edge from the current system to that system with weight of (number of jumps to reach that system) * (cost per jump) - (difference in price of the commodity) (i.e. profit to be made by buying in the current system and selling in the destination system)

I believe the technical description of what I'm after is (for question 1): given the above digraph what's the negative cycle with the lowest average cost per edge.

I realize I can use a breadth-first search to answer questions 3 and 4 as long as the maximum number of jumps is small enough that I don't run out of memory, but I suspect it won't be practical to answer 1 or 2 this way.

I've read though the Solving Problems by Searching chapter in AI: A Modern Approach but as far as I can tell the algorithms there require positive edge weights.

A bit of Googling found me the Bellman–Ford algorithm and while that supports negative edge weights my understanding is that it doesn't give accurate costs when negative cycles are involved.

Are there any algorithms I can use to solve this problem more efficiently?

答:
This is not a traveling salesman problem if there is no prohibition on revisiting a system.

The problem for Question 1 is canonically referred to as the minimum mean cycle problem, which has polynomial-time algorithms. This is a subroutine in some min-cost flow algorithms.

Question 2 is sort of ill-defined because there won't be a best route in general; you'll want to fly to the best loop, do it a bunch of times (the more the better), and fly back.

Questions 3 and 4 can be addressed by expanding the digraph with a time dimension (where one unit of "time" is one jump) and then computing shortest paths on the resulting acyclic digraph.


答:
Depending on the architecture your current web app is using. When dealing with multiple channels like in your case, it's recommended to have a core system that manages business logic and data access. On top of it, you would stack your thin clients like web app, mobile app, android app, etc...

I would say if you can, refactor the web app as much as you can to separate the business logic and presentation layer. Then utilize business logic layer as a common, while maintaining two different projects for the clients.

Title: Mobile Web App - combines with exist web app or separate them

Body:
The company I work for already has a fully functional web app that is written in java using JSF framework. I'm now in the process of creating a mobile version of this web app and having some general questions on where to put this mobile web app.

Should this mobile web app be a separate project, packaged in a different war, and installed as separate app in server or should it be part of the existing web app, packaged in the same war, and installed as same app in server?

Should the mobile web app uses existing web app's jsf Manage Beans? For example, we already have an order entry app that consists of several jsf Manage Beans and jsf pages. To create the mobile version of this app, should I simply create new mobile version of jsf pages but uses all the exist jsf Manage Beans in those mobile jsf pages? Will I run into problem because mobile web app's page-flow might be different from the web app's page-flow? But if I don't reuse, it seems like there will be a lot of duplicate code.


问:
Design Pattern for retry and error handling
I'm trying to find a good design pattern, or perhaps series of patterns, for injecting error handling and retry handling when getting data from a webservice.

For instance, I have:

```<code>do {
    //get the data here
    data = Datagetter.getMyData(request)

    if(data.hasError())
    {
        //handle error
    }
} while(shouldRetry());
</code>```

And I am trying to figure out a way to inject the mechanism the discovers and deals with any error, as well as the mechanism that handles how retrying works (should I wait? have I retried enough? should I modify a request parameter? etc).

I would guess I am not the first person faced with this, and there is a way to do this I just haven't discovered yet.

I have looked into chain-of-responsibility and strategy as possible solutions, but I can't seem to quite finagle them to work.

答: I'm afraid you need to code the retrying logic yourself. However, this can be separated from the actual service call by utilizing the Proxy pattern. The RetryingProxy wraps the actual service and implements the error handling and retrying policy you need.</p>


问:
Unit Testing for mapping int to string
How should one unit test a function which (among other things) maps an integer to a string?

If the function were to map 0 => string0, 1 => string1, 2 => string2, should I test for each of 0, 1, and 2? Or should I just test one of these cases?

答: If the function does several different things (and the description "...a function which (among other things) maps an integer to a string" indicates that yours does), you should probably divide it into several functions and test each of them separately. Then, as Daniel T. suggested, make sure to test every branch through the function(s).

Title: Unit Testing for mapping int to string


答:
How about using enums(mapper int to string) and you don't need to unit test anything.

```<code>enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
</code>```

Now let's assume your mapper is used by some method that returns different results based on the mapper. Here is how I would test it.

Programatically get all the values in the mapper.

Iterate through each and call your method with that value.

Assert after each response.

The example above would do well if you are loading something from filesystem that corresponds to your enum values or something similar. Your situation could vary.

Title: Unit Testing for mapping int to string

Body:
How should one unit test a function which (among other things) maps an integer to a string?

If the function were to map 0 => string0, 1 => string1, 2 => string2, should I test for each of 0, 1, and 2? Or should I just test one of these cases?

Body:
How about using enums(mapper int to string) and you don't need to unit test anything.

enum Days {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};

Now let's assume your mapper is used by some method that returns different results based on the mapper. Here is how I would test it.

Programatically get all the values in the mapper.

Iterate through each and call your method with that value.

Assert after each response.

The example above would do well if you are loading something from filesystem that corresponds to your enum values or something similar. Your situation could vary.


问:
Flag arguments in an html factory class
I have been told that flag arguments(boolean arguments) are a bad thing because it complicates the signature of the method and means that the method does more than one thing.

An issue I have with this rule is what if I have a html factory class that builds raw html from arguments passed in. Then lets say I want an option to make the form element required. This would obviously make most sense as a boolean argument. But this is contradictory to what I have been told.

So my questions is: is this an exception to this rule, does this rule even make sense, or what is the correct way to do a required option in an html factory class?

答:
Every rule in programming is just a guidance(Just like this exact statement, I bet there are a few rules that are not a guidance :)). There are many ways of achieving the same thing, but some are better than others.

In your case, using flags is totally fine, if you see that they are truly flags(yours seems to be).

Another important moment to consider is that when yo have a flag, it's best when it is used in the method directly, and not completely changing the scope of execution for everything below. A.K.A Simple flag - in your case it's as simple as it gets:

```<code>return String.Format("<input type=\"text\" class=\"required-{0}\" />", isRequired);
</code>```

Title: Flag arguments in an html factory class

Body:
Every rule in programming is just a guidance(Just like this exact statement, I bet there are a few rules that are not a guidance :)). There are many ways of achieving the same thing, but some are better than others.

In your case, using flags is totally fine, if you see that they are truly flags(yours seems to be).

Another important moment to consider is that when yo have a flag, it's best when it is used in the method directly, and not completely changing the scope of execution for everything below. A.K.A Simple flag - in your case it's as simple as it gets:

return String.Format("<input type=\"text\" class=\"required-{0}\" />", isRequired);


问:
(Partially) Sorting a lazy-evaluated collection
So I'm trying to implement a lazy-evaluating data type (in PHP, though that shouldn't matter any) where you can queue up actions to take on a set of data. This data can come (theoretically) from any traversable object: arrays, generators, and other iterable objects.

So for instance, given a $collection object containing a unsorted array of integers, you could call methods on that object like map($callback) or filter($callback) and it will return a new Collection instance with the action queue of the original collection appended with the called method. No queued actions are executed until the absolute last possible moment, e.g. when the data is actually going to be used for output, reduction to a simple value, and even methods like some/every/find only iterate as much as they need to. This restriction is made easier to implement by the collection (currently) not exposing any sort of index access interface.

The underlying implementation once execution is triggered will try and iterate over the underlying data set as few times as possible by logically grouping the queued operations where possible to avoid creating any intermediate representations of the data as much as possible. So if you have multiple map() operations set up, then it'll compose those. Filter operations can be grouped in to this single execution loop too, all it means is that when the filter/rejection test function fails then the execution ends for that iteration element.

And this all works, right up until one edge case: sorting. Sorting (unless there's a better idea I'm missing here) requires a separate iteration cycle to begin so that the array can begin. Which I don't mind doing, except in certain cases like where I want only, say, exclusively the first n elements of the sorted collection. At that point, it seems to me that there's no way to know what those values are without sorting the entire collection. Is there any way to avoid that? Otherwise it's going to be a waste of (most of) the advantages of lazy evaluation, and I'd like to avoid that...

答:
In short, no, there is no way to do sorting on an incomplete collection unless you will delay sorting until the very end wen the collection is already present.

Longer version:
Sorting by definition involves evaluating the entire set of items and arranging them in the right order. I doubt you can do sorting on the the collection without having the entire collection instantiated.

If your collection consists of rather large complex objects, consider having object metadata that is required for sorting available upon sorting, and load the rest of the object data as required later on into the execution cycle.


答:
Taking clues from LINQ, a typical way to workaround this fundamental impossibility is to implement a Take function, which takes the first N values from the lazy collection (or enumerator) and then process only those N values.

To use it, the user must specify how many values to "take" each time.

Collections which are already sorted or histogrammed (binned in a sorted order) can perform lazy take, because the sorting has already been done.

In some limited use cases, one could do something similar to:

Suppose the values are integers in the range 0 - 99, inclusive.

To retrieve all items in the range 0 - 9, do a Filter between 0 and 9 inclusive, whose result is then sorted.

To retrieve all items in the next range of 10 - 19, do another Filter between 10 and 19 inclusive, and then sort that.

This requires some prior knowledge of the numerical distribution of data, but it does not require a complete sorting (ranking) of all of the data.

In particular, this range filtering approach will not be able to produce correct result unless a lower bound on the numerical data is known. (Any lower bound will work.)

Title: (Partially) Sorting a lazy-evaluated collection

Body:
So I'm trying to implement a lazy-evaluating data type (in PHP, though that shouldn't matter any) where you can queue up actions to take on a set of data. This data can come (theoretically) from any traversable object: arrays, generators, and other iterable objects.

So for instance, given a $collection object containing a unsorted array of integers, you could call methods on that object like map($callback) or filter($callback) and it will return a new Collection instance with the action queue of the original collection appended with the called method. No queued actions are executed until the absolute last possible moment, e.g. when the data is actually going to be used for output, reduction to a simple value, and even methods like some/every/find only iterate as much as they need to. This restriction is made easier to implement by the collection (currently) not exposing any sort of index access interface.

The underlying implementation once execution is triggered will try and iterate over the underlying data set as few times as possible by logically grouping the queued operations where possible to avoid creating any intermediate representations of the data as much as possible. So if you have multiple map() operations set up, then it'll compose those. Filter operations can be grouped in to this single execution loop too, all it means is that when the filter/rejection test function fails then the execution ends for that iteration element.

And this all works, right up until one edge case: sorting. Sorting (unless there's a better idea I'm missing here) requires a separate iteration cycle to begin so that the array can begin. Which I don't mind doing, except in certain cases like where I want only, say, exclusively the first n elements of the sorted collection. At that point, it seems to me that there's no way to know what those values are without sorting the entire collection. Is there any way to avoid that? Otherwise it's going to be a waste of (most of) the advantages of lazy evaluation, and I'd like to avoid that...


问:
How to avoid calling String.Replace() in a loop?
I am building a very simple email templating system in C#, and it works amazingly, but  I have a personal issue with the way I designed it:

Template looks like this:

Hello {UserName},
Welcome to ....
```
<p>And the way I am replacing the tokens with values is this:</p>
```foreach (var variable in variables)
{
    str = str.Replace("{" + variable.Key + "}", variable.Value);
}
```

Well, to say the least, I hate it. Is there any more efficient way of dealing with tokens?

UPDATE: Found this article, and looks like both REGEX and StringBuilder are slower than String.Replace();

StringBuilder.Replace VS REGEX.Replace vs String.Replacte

答:
I don't think you need tokens.

One possible way to improve things is to look at each character in input the text (the templates) only once.

Search through the string from start to finish (once), and assemble a new string as follows: from the start, search for {, followed by identifier characters, then }.  Move the string text before the { to the new string, then look up the identifier in a dictionary and move the replacement to the new string.  Start over looking for { from where you left off last.

This way you're not scanning the input text over and over.  You could tokenize the input string, but I don't think it helps compared to this suggestion.

The point here is to think about how things scale (think O() descriptions).  If some template is very large then you're scanning that text once for each str.Replace operation. Further, if the number of variables is very large, then you're scanning a large input text as many times as the number of variables.  With this suggestion, you scan the input text only once, no matter how many variables.

ContentLicense: CC BY-SA 4.0


问:
Printing a large number of images from the browser
I have a web application where I need to create, and then print, potentially tens of thousands of images at once. I need to support most modern Mac/PC browsers, but not mobile or tablet. My current plan is to:

Create a web page where the user can select image creation options.

When user finishes selection, click a button which will instruct the server to generate all of the images.

Have the server generate an HTML page with all of the images generated, using appropriate CSS styles to ensure one image per page is printed.

Load the HTML into a hidden iFrame on the initial page

Print it using the technique outlined here

I know how to do all of this. However, I'm really worried that if there are enough images it will run the client's browser out of memory. If I have, say, 100,000 pages to print - are browsers smart enough to only download what it's spooling to the printer? Or does everything get downloaded immediately?

答: I don't have a solution, but contributing information about what I've tried. I'm also trying to do this, to print thumbnails of thousands of video clips. I wrote a script to make thumbnails watermarked with the disk image and clip name. Then I wrote another CGI script to display all the "*jpg" in a directory. All the directories from one year of clips could display on the same web page -- if the browser doesn't run out memory. Chrome never finishes rendering. Firefox renders all the thumbnails correctly, but doesn't "Print to PDF" correctly, or "Print to PostScript" correctly....there are "gaps" or white space where on the HTML render in the browser, there -were- images. I tried increasing cache/memory, etc. but still gaps if I display more than about 100 directories of thumbnails. It's only about 240MB worth of images, but it's about 10,000 little images. I think it's the number of images, not the disk space or RAM needed. </p>


问:
How to model complex event in event sourcing?
Lets say that we have a user (like super-hero) that want to see all wars that is going on in a world so that he can stop them. He can't prevent them all, because he needs to sleep sometimes and so on. But if a war have happened when he was asleep, he wants to know about that (so he can punish ones who started it for example).

So if war started he wants to see where it have happened and when. And also all events about this war, like some battles for example.

So he wants software that can present him this information at some 'war table' where he can see all wars that he still haven't reacted to in some way.

And that's a software that I need to write.

So lets say that I have some software that monitors some state and based on lower level events generates events like 'War started', 'War ended', 'Battle started', 'Battle ended', 'War changed location' etc.

The problem that puzzles me is that at the time when War started - war is a process, not an event. Because war is still going on. But after the 'War ended' event we can say that this process in ended and now it is a event.

To be more concrete. Lets say that the sequence of events is:

'War1 started at location x1'
'War2 started at location x2'
'War1 changed location to x4'
'War2 changed location to x5'
'War1 have a new battle started at location x3'
'War1 have a new battle ended at location x3'
'War1 ended'

But the user doesn't want to see this as a sequence.
What he wants to see is something like this

'War1 is going on at location x1'
'War2 is going on at location x2'

Then he wants the first row to change according to next event

'War1 is going on at location x4'
'War2 is going on at location x2'

and so on

'War1 is going on at location x4'
'War2 is going on at location x5'

and so on until this wars would end.

'War1 was at location 'some location''
'War2 was at location 'some different location''

As you can see war1 and war2 is events now.

After war is ended super-hero still want to know all information about it if he want to, but in this war-table he basically wants to see current information about war process.

Right now the solution is to think about this war process as process, that can be still going or have been already ended. The problem is that in this case if we would want to monitor some event that is different then war and more simple (like it some switch that can be just on or off) we would have model that as a process that have a start time and stop time. Which is... strange I think.

I thought about different solution. Instead of displaying processes display lower level events grouped by subject.

Like 'War 1 have started' and 'War 1 have ended' have the same subject - 'War 1' process.

But not all events in our system would have process as a subject and... I'm kink of lost here.

Maybe someone already have done something like that? What could be the correct approach to that?

答:
I have several thoughts on your question.

What your talking about is done in a larger context with patterns like CQRS (Command Query Responsibility Separation) and Event Sourcing, and the "lambda architecture".

These architectural patterns address scale, fault tolerance/recovery.  Essentially Event Sourcing captures and persists events in the system as append-only log structure, some process reads the logs and feeds to a database of some sort that maintains the current state translating each event into an update of the database; fault tolerance and recovery from the database crash are accomplished by re-reading the event log.  Other parts of the architecture maintain different representations of the current state, one might be write-optimized (normalized) another read-optimized (denormalized as per application queries).

While these patterns are probably applied at scale larger than you are attempting, the idea behind them is similar -- to translate between different representations, which start with events and go toward current state (in several representations for different purposes).

On another note, I would say that an event is associated with a time (when the event occured), and a process with a start time and end time.  Some processes are ongoing, but all that means is that we don't know their end time (yet).  Just because a process ends (i.e we learn their end time) doesn't convert it to an event, it is still a process.

You should definitely try to have a "subject" of your messages.  That will help translating events to current state.  In my opinion, information modeling should attempt to capture and represent facts.  Facts can be represented by sentences, in one simple example, by subject, verb, object.  These patterns help a lot when trying to capture and translate meanings between different forms (i.e. events and current state)

Maybe you could give an example of an event that doesn't have a subject, and we could discuss.


答:
Another way to solve this is using regular expressions:

```<code>string LookupVariable(Match match) {
   string name = match.Groups[1].Value;
   return variables[name];
}

str = (new Regex("{([^}]*)}")).Replace(str, LookupVariable);
</code>```

I don't actually code C#, so my syntax is almost certainly not quite right.

Title: How to avoid calling String.Replace() in a loop?

Body:
I am building a very simple email templating system in C#, and it works amazingly, but  I have a personal issue with the way I designed it:

Template looks like this:

Hello {UserName},
Welcome to ....
```
<p>And the way I am replacing the tokens with values is this:</p>
```foreach (var variable in variables)
{
    str = str.Replace("{" + variable.Key + "}", variable.Value);
}
```

Well, to say the least, I hate it. Is there any more efficient way of dealing with tokens?

UPDATE: Found this article, and looks like both REGEX and StringBuilder are slower than String.Replace();

StringBuilder.Replace VS REGEX.Replace vs String.Replacte

Body:
Another way to solve this is using regular expressions:

string LookupVariable(Match match) {
   string name = match.Groups[1].Value;
   return variables[name];
}

str = (new Regex("{([^}]*)}")).Replace(str, LookupVariable);

I don't actually code C#, so my syntax is almost certainly not quite right.


问:
Why use Android Fragments?
I have read the documentation and some other questions' threads about this topic and I don't really feel convinced; I don't see clearly the limits of use of this technique.

Fragments are now seen as a Best Practice; every Activity should be basically a support for one or more Fragments and not call a layout directly.

Fragments are created in order to:

allow the Activity to use many fragments, to change between them, to reuse these units... ==> the Fragment is totally dependent to the Context of an activity , so if I need something generic that I can reuse and handle in many Activities, I can create my own custom layouts or Views ... I will not care about this additional Complexity Developing Layer that fragments would add.

a better handling to different resolution ==> OK for tablets/phones in case of long process that we can show two (or more) fragments in the same Activity in Tablets, and one by one in phones. But why would I use fragments always ?

handling callbacks to navigate between Fragments (i.e: if the user is Logged-in I show a fragment else I show another fragment). ===> Just try to see how many bugs facebook SDK Log-in have because of this, to understand that it is really (?) ...

considering that an Android Application is based on Activities... Adding another life cycles in the Activity would be better to design an Application... I mean the modules, the scenarios, the data management and the connectivity would be better designed, in that way. ===> This is an answer of someone who's used to see the Android SDK and Android Framework with a Fragments vision. I don't think it's wrong, but I am not sure it will give good results... And it is really abstract...

====> Why would I complicate my life, coding more, in using them always? else, why is it a best practice if it's just a tool for some cases? what are these cases?

答: If there's a "gateway" use case for fragment skeptics, it's probably dialogs.  The long-deprecated methods showDialog(...), onCreateDialog(...), etc., were nice in that the framework would call them to automatically destroy and recreate your dialogs when the hosting activity was destroyed and recreated.  If you create your own dialogs directly, you have to manage all that stuff yourself.  But if you use a DialogFragment, you can once again let the framework manage them for you.  In this case, fragments can greatly simplify your coding.

Title: Why use Android Fragments?


问:
Filtering additions to a list
Hopefully Iʼm posting this in the right SX, and Iʼve tagged it correctly.

I have a legacy system that Iʼm making additions to which contains a custom list object.

This list object can contain two types of elements, another list, or an item.

Part of a current task requires that I make an adjustment to the list in such a way as to exclude the addition of items or lists dependent on their type or whether they are in another list of a different or the same type.

An array of items can be passed to the list object, and theyʼre added one at a time in a loop.

I would like to implement the rules as to whether an item can be added to a list as a separate business rules class where I pass the list and item to the rule class and receive a Boolean value back as to whether the item can be added to the list or not. Something along the lines of:

```<code>function InsertItems(ArrayOfItems)
    for each item in ArrayOfItems
        if ruler.CanItemBeAddedToList(item, list) then
            add(item)
        end if
    end for
end function
</code>```

The language used for the legacy system is VB.NET hence the BASIC style of the pseudo-code.

In general terms is it best to have a separate class to hold a rule such as this, or should it be part of the list class or the item class? That said the more I think about it the more I prefer a rule-class to make the decision rather than embedding the decision in the list. I donʼt believe it should be embedded in the item class. Though you can write it nicely e.g.

```<code>if item.CanBeAddedTo(list) then
   add(item)
end if
</code>```

But this effectively means that the item must know about lists, which is not good from a coupling point-of-view. On the other hand should a list know about items especially given that the list is not a generic one?

答:
From my point of view the method "CanBeAdded" should neither be in the item, nor in a special rulter. It should be in the list itself. Therefore:

```<code>if list.CanAdd(item)
    ...
end
</code>```

The List implementation then should have a set (probably implemented as list) of rules, that define whether an item can be added.

```<code>function CanAdd(item) As Boolean
    for each rule in ListOfRules
        if Not(rule.IsFulFilledBy(this, item))
           return False
        end
    end
    return True
end
</code>```

This allows the system to be open to new rules, without having to be changed (Open/Closed-Principle).

I beg to excuse any syntactical mistakes. I am not very familiar with BASIC style languages.

Title: Filtering additions to a list

Body:
From my point of view the method "CanBeAdded" should neither be in the item, nor in a special rulter. It should be in the list itself. Therefore:

if list.CanAdd(item)
    ...
end

The List implementation then should have a set (probably implemented as list) of rules, that define whether an item can be added.

function CanAdd(item) As Boolean
    for each rule in ListOfRules
        if Not(rule.IsFulFilledBy(this, item))
           return False
        end
    end
    return True
end

This allows the system to be open to new rules, without having to be changed (Open/Closed-Principle).

I beg to excuse any syntactical mistakes. I am not very familiar with BASIC style languages.


问:
Why can't I use an operator like plus sign to concatenate strings?
Why in Objective-C we should be typing explicit references to methods like stringByAppendingString to concatenate strings, when in some other languages we can use operators for that?

For example, Java and C++ let us just concatenate strings in a similar fashion to the way we make our programs add two numbers.

答:
+ is the symbol for addition. Concatenation is not addition. Addition is commutative (a + b == b + a), concatenation isn't ("Hello" + "World" != "World" + "Hello").

Using + for concatenation is just wrong. Other languages use other operators for that reason, e.g. Haskell uses ++, IMP, Perl and PHP use ., Ada and Visual Basic use &, PL/I uses ||, Standard ML uses ^, Smalltalk uses ,, and Fortress has three different string concatenation operators “Hello” ∥ “World” (simple string concatenation), “Hello” ||| “World” (string concatenation with whitespace in between the two strings unless one of them is empty), and the juxtaposition operator for strings is overloaded as an alias for |||: “Hello” “World”.

By the way: I highly doubt Apple is responsible for this decision. String concatenation is such an important operation that I am pretty sure it was added long before Apple took over development of Objective-C, most likely even before it was used at NeXT.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
Code in your native language (not English), write documentation in your native language. And then outsource the project to an Indian company.

That's evil for you!

P.S.: For the record, it happened, and the Indians didn't find it very funny.

Title: Is anything in programming truly evil?


问:
log method calls per object
How to log method calls on a per object basis for a particular class?
I.e. after instanciating a = myClass() I somehow want to keep a log for what methods have been called on a like

```<code>a.reverse()
a.loadNewData()
a.substract(somenparray)
</code>```

later I want be able to look at this object's history/log e.g. a.log().
All logging stuff I've seen so far could be used to log all function calls but not restricted to a per object basis.

答:
Here is one way to do it, which increments a collections.Counter every time a callable attribute is accessed:

```<code>class LoggingMixIn:

    def __init__(self, *args, **kwargs):
        self._log = Counter()
        super().__init__(*args, **kwargs)

    def __getattribute__(self, name):
        attr = super().__getattribute__(name)
        if callable(attr):
            self._log[name] += 1
        return attr

    def log(self):
        return self._log
</code>```

In use:

```<code>>>> from collections import Counter
>>> class Demo(LoggingMixIn):
        def method1(self):
            pass
        def method2(self):
            pass

>>> d = Demo()
>>> d.method1()
>>> d.method2()
>>> d.method2()
>>> d.log()
Counter({'method2': 2, 'method1': 1, 'log': 1})
</code>```

You can special-case name == 'log' if you don't want to log calls to log. However, note that this won't log calls to the instance itself, or to a property:

```<code>>>> class Demo(LoggingMixIn):
    def method(self):
        pass
    @property
    def property(self):
        pass
    def __call__(self):
        pass

>>> d = Demo()
>>> d.method()
>>> d.property
>>> d()
>>> d.log()
Counter({'log': 1, 'method': 1})
</code>```

Title: log method calls per object

Body:
Here is one way to do it, which increments a collections.Counter every time a callable attribute is accessed:

class LoggingMixIn:

    def __init__(self, *args, **kwargs):
        self._log = Counter()
        super().__init__(*args, **kwargs)

    def __getattribute__(self, name):
        attr = super().__getattribute__(name)
        if callable(attr):
            self._log[name] += 1
        return attr

    def log(self):
        return self._log

In use:

>>> from collections import Counter
>>> class Demo(LoggingMixIn):
        def method1(self):
            pass
        def method2(self):
            pass

>>> d = Demo()
>>> d.method1()
>>> d.method2()
>>> d.method2()
>>> d.log()
Counter({'method2': 2, 'method1': 1, 'log': 1})

You can special-case name == 'log' if you don't want to log calls to log. However, note that this won't log calls to the instance itself, or to a property:

>>> class Demo(LoggingMixIn):
    def method(self):
        pass
    @property
    def property(self):
        pass
    def __call__(self):
        pass

>>> d = Demo()
>>> d.method()
>>> d.property
>>> d()
>>> d.log()
Counter({'log': 1, 'method': 1})


问:
Java - Best way to set properties of an object
I don't know if there is any difference in performance, or its just a matter of choice, but I am a perfectionist like that, and I'd like to know.

Lets say you have the object HolySheet. You can set its properties in three ways:

```<code>HolySheet sheet = new HolySheet().setPropertyOne("asd").setPropertyTwo("foo");
</code>```

or

```<code>HolySheet sheet = new HolySheet();
sheet.setPropertyOne("bdg")
     .setPropertyTwo("harry potter");
</code>```

or

```<code>HolySheet sheet = new HolySheet();
sheet.setPropertyOne("bdg");
sheet.setPropertyTwo("harry potter");
</code>```

Is there any difference between these 3 ways? I am interested in performance mostly.

答:
If you need to ask the question, you don't need to know the answer.

If you had a profiler, profiled your code, and found this to be a hotspot, you could trivially find out the answer yourself by simply changing the code and profiling again.

Since you haven't done that, we can readily deduce that in fact, you have no such hotspot and no such profiler, and therefore, even if one of them was theoretically faster, this would be a meaningless waste of your time.

The important thing to take away is not to waste time micro-optimizing random chunks of code, because you'll spend time for literally no useful reward whatsoever. Which one of these is faster is irrelevant.


问:
Create new object or reset every property?
```<code> public class MyClass
    {
        public object Prop1 { get; set; }

        public object Prop2 { get; set; }

        public object Prop3 { get; set; }
    }
</code>```

Suppose I have an object myObject of MyClass and I need to reset its properties, is it better to create a new object or reassign each property? Assume I don't have any additional use with the old instance.

```<code>myObject = new MyClass();
</code>```

or

```<code>myObject.Prop1 = null;
myObject.Prop2 = null;
myObject.Prop3 = null;
</code>```

答:
Instantiating a new object is always better, then you have 1 place to initialise the properties (the constructor) and can easily update it.

Imagine you add a new property to the class, you would rather update the constructor than add a new method that also re-initialises all properties.

Now, there are cases where you might want to re-use an object, one where a property is very expensive to re-initialise and you'd want to keep it. This would be more specialist however, and you'd have special methods to reinitialise all other properties. You'd still want to create a new object sometimes even for this situation.


答:
In some languages, the concatenation operator is just syntactic sugar. For example, in C#:

```<code>var a = b + c;
</code>```

and:

```<code>var a = string.Concat(b, c);
</code>```

are compiled to the same Intermediary Language code if b and c are strings: + is here just to make developers' life easier.

Syntactic sugar might be nice, but it also means that the company developing the language should spend time:

Redesigning the language to include the specific syntactic sugar feature; this alone is an extremely complicated task.

Modifying the compiler so it can deal with the new syntax.

Documenting the new behavior, including the fact that + is now commutative in some cases, but not in others and translating the documentation in every supported language.

Dealing with all the edge cases; for instance, what is the result of "123" + 4, and what is the result of 1 + "234"?

Changing all the IDEs to support the new syntax.

Thoroughly testing the compiler and the IDEs.

Adding such feature also means that there would be inevitably three types of developers:

The ones who will understand that the operator is syntactic sugar and how is it translated by the compiler,

The ones who won't know the internals, but know how to use the operator and what it involves,

The ones who won't know the internals and ask questions such as: “I believe string addition is slow, so I will rewrite my entire code base to use string.Concat instead. Am I on the right track?”

Thus, instead of making everyone's lives easier, you are just spending dozens of thousands of dollars developing a feature which only obfuscates the language.

This is also why languages tend to use as few keywords as possible. More keywords means more opportunities for bugs and unclear situations, and more difficult to learn language with more rules.

Title: Why can't I use an operator like plus sign to concatenate strings?

Body:
Why in Objective-C we should be typing explicit references to methods like stringByAppendingString to concatenate strings, when in some other languages we can use operators for that?

For example, Java and C++ let us just concatenate strings in a similar fashion to the way we make our programs add two numbers.

Body:
In some languages, the concatenation operator is just syntactic sugar. For example, in C#:

var a = b + c;

and:

var a = string.Concat(b, c);

are compiled to the same Intermediary Language code if b and c are strings: + is here just to make developers' life easier.

Syntactic sugar might be nice, but it also means that the company developing the language should spend time:

Redesigning the language to include the specific syntactic sugar feature; this alone is an extremely complicated task.

Modifying the compiler so it can deal with the new syntax.

Documenting the new behavior, including the fact that + is now commutative in some cases, but not in others and translating the documentation in every supported language.

Dealing with all the edge cases; for instance, what is the result of "123" + 4, and what is the result of 1 + "234"?

Changing all the IDEs to support the new syntax.

Thoroughly testing the compiler and the IDEs.

Adding such feature also means that there would be inevitably three types of developers:

The ones who will understand that the operator is syntactic sugar and how is it translated by the compiler,

The ones who won't know the internals, but know how to use the operator and what it involves,

The ones who won't know the internals and ask questions such as: “I believe string addition is slow, so I will rewrite my entire code base to use string.Concat instead. Am I on the right track?”

Thus, instead of making everyone's lives easier, you are just spending dozens of thousands of dollars developing a feature which only obfuscates the language.

This is also why languages tend to use as few keywords as possible. More keywords means more opportunities for bugs and unclear situations, and more difficult to learn language with more rules.


问:
How do you keep the size of your application down (memory usage and physical storage size)?
I have a personal project that I'm working on although it's quite audio and graphic-intense and I was wondering if you guys had any suggestions or solutions as to how one could keep the size and memory-usage of their application to a minimum? My application is an iPhone application and, as Apple always make clear, the application is only allowed to use a certain amount of memory (in terms of performance and actual size).</p>

答:
Start looking for more compression using other formats when dealing with audio and video. Also images tend to have compressed version like jpeg. But if your application need multimedia, it will be quite heavy.

Also maybe try asking the same on stackoverflow forums, there you may find a more expert solution