问:
Proper use of the GPL when using a library covered by an older version
I have a piece of software that I have been working on for a while now. You can find it here. Since it is now at a stage where it could potentially be useful to other researchers, I decided to cover it by the GPL.

While most of it is code that I wrote myself, one set of functions, contained in butterworth.c and butterworth.h, are not - they are a library of functions I found on this website, and are covered by the GPLv2. The rest I have (tried to) cover with the GPLv3.

I suspect that having two versions of the GPL in the same project is not OK, so what is the proper way to cover the contents of butterworth.c in my project while still giving credit where it is due to the original programmers who wrote it?

I suppose, in addition, is there anything wrong/missing with the way I have set up the GPLv3 in the rest of the project? Currently it is just a comment block at the start of all .c files.

答:
Per the comment you left, the code you are using but do not own is licensed under GPLv2 or any later version. That clause may be omitted; the Linux kernel is a famous example of a project that is only licensed as GPLv2. However, it appears that clause is intact in this instance.

Based on the information in the question, it appears that you can license the whole project (including the files in question) under the GPLv3.

Please keep in mind that these are licensing terms. Copyright is still owned by the original author unless reassigned. The fact that you are relicensing the code does not change who actually owns the "butterworth" code.

To remove any potential ambiguity about legal rights, each file should have both a copyright and license notice near the top. You can have a standard GPLv3 notice (the FSF has boilerplate text for this on their web site) but leave the butterworth copyright notice intact.


问:
When did Undefined Behavior in C jump the causality barrier
Some hyper-modern C compilers will infer that if a program will invoke Undefined Behavior when given certain inputs, such inputs will never be received.  Consequently, any code which would be irrelevant unless such inputs are received may be eliminated.

As a simple example, given:

```<code>void foo(uint32_t);

uint32_t rotateleft(uint_t value, uint32_t amount)
{
  return (value << amount) | (value >> (32-amount));
}

uint32_t blah(uint32_t x, uint32_t y)
{
  if (y != 0) foo(y);
  return rotateleft(x,y);
}
</code>```

a compiler may infer that because evaluation of value >> (32-amount) will yield Undefined Behavior when amount is zero, function blah will never be called with y equal to zero; the call to foo can thus be made unconditional.

From what I can tell, this philosophy seems to have caught hold sometime around 2010.  The earliest evidence I've seen of its roots goes back to 2009, and it's been enshrined in the C11 standard which explicitly states that if Undefined Behavior occurs at any point in a program's execution, the behavior of the entire program retroactively becomes undefined.

Was the notion that compilers should attempt to use Undefined Behavior to justify reverse-causal optimizations (i.e. the Undefined Behavior in the rotateleft function should cause the compiler to assume that blah must have been called with a non-zero y, whether or not anything would ever cause y to hold a non-zero value) seriously advocated prior to 2009?  When was such a thing first seriously proposed as an optimization technique?

[Addendum]

Some compilers have, even in the 20th Century, included options to enable certain kinds of inferences about loops and the values computed therein.  For example, given

```<code>int i; int total=0;
for (i=n; i>=0; i--)
{
  doSomething();
  total += i*1000;
}
</code>```

a compiler, even without the optional inferences, might rewrite it as:

```<code>int i; int total=0; int x1000;
for (i=n, x1000=n*1000; i>0; i--, x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

since the behavior of that code would precisely match the original, even if the compiler specified that int values always wrap in mod-65536 two's-complement fashion.  The additional-inference option would let the compiler recognize that since i and x1000 should cross zero at the same time, the former variable can be eliminated:

```<code>int total=0; int x1000;
for (x1000=n*1000; x1000 > 0; x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

On a system where int values wrapped mod 65536, an attempt to run either of the first two loops with n equal to 33 would result in doSomething() being invoked 33 times.  The last loop, by contrast, wouldn't invoke doSomething() at all, even though the first invocation of doSomething() would have preceded any arithmetic overflow.  Such a behavior might be considered "non-causal", but the effects are reasonably well constrained and there many cases where the behavior would be demonstrably harmless (in cases where a function is required to yield some value when given any input, but the value may be arbitrary if the input is invalid, having the loop finish faster when given an invalid value of n would actually be beneficial).  Further, compiler documentation tended to be apologetic for the fact that it would change the behavior of any programs--even those that engaged in UB.

I'm interested in when compiler writers' attitudes changed away from the idea that platforms should when practical document some usable behavioral constraints even in cases not mandated by the Standard, to the idea that any constructs which would rely upon any behaviors not mandated by the Standard should be branded illegitimate even if on most existing compilers it would work as well or better than any strictly-compliant code meeting the same requirements (often allowing optimizations which would not be possible in strictly-compliant code).

答:
This is because there is a bug in your code:

```<code>uint32_t blah(uint32_t x, uint32_t y)
{
    if (y != 0)
    {
        foo(y);
        return x; ////// missing return here //////
    }
    return rotateleft(x, y);
}
</code>```

In other words, it only jumps the causality barrier if the compiler sees that, given certain inputs, you are invoking undefined behavior beyond doubt.

By returning right before the invocation of undefined behavior, you tell the compiler that you are consciously preventing that undefined behavior from executing, and the compiler acknowledges that.

In other words, when you have a compiler that tries to enforce the specification in a very strict way, you have to implement every possible argument validation in your code. Furthermore, these validation must occur before the invocation of the said undefined behavior.

Wait! And there is more!

Now, with compilers doing these super-crazy yet super-logical things, it is your imperative to tell the compiler that a function isn't supposed to continue execution. Thus, the noreturn keyword on the foo() function now becomes mandatory.

ContentLicense: CC BY-SA 3.0

Body:
This is because there is a bug in your code:

uint32_t blah(uint32_t x, uint32_t y)
{
    if (y != 0)
    {
        foo(y);
        return x; ////// missing return here //////
    }
    return rotateleft(x, y);
}

In other words, it only jumps the causality barrier if the compiler sees that, given certain inputs, you are invoking undefined behavior beyond doubt.

By returning right before the invocation of undefined behavior, you tell the compiler that you are consciously preventing that undefined behavior from executing, and the compiler acknowledges that.

In other words, when you have a compiler that tries to enforce the specification in a very strict way, you have to implement every possible argument validation in your code. Furthermore, these validation must occur before the invocation of the said undefined behavior.

Wait! And there is more!

Now, with compilers doing these super-crazy yet super-logical things, it is your imperative to tell the compiler that a function isn't supposed to continue execution. Thus, the noreturn keyword on the foo() function now becomes mandatory.


问:
Good practice to save the last time user accessed the app
Using a JWT authentication, the user doesn't have to log in each time he uses my app.

I would like to save in DB the last time the user used/opened the app.

Technically, I have a set of REST API that could audit each request and save in database the timestamp corresponding to the current user access but ... for each request?!

What is a good practice to store this information without involving database each time the user makes a request?

答:
You can set a threshold.

For instance, you can store that someone visited at 14:00PM, and then audit if the difference between then and the current time is more than 30 minutes, so you have 2 updates per hour at most.

If you have a stateful service, another approach would be to store the time of each request in memory (default session driver, Redis, Memcache, whatever).

That way, you can detect when they leave your app and store their last time just once, at the end.

Update:

Another way would be to serve a request timestamp with your API tokens if you use, say, JWT. If not, you can still send cookies or store them in user's localStorage. Then they will send you their last access time with each request and you can utilize the first suggestion without having to touch the database.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答: I use them for high level quick sketches in the beginning, even if it's only me working on something. Beyond that they tend not to get used.</p>

ContentLicense: CC BY-SA 2.5

Title: White Boards -- Who Uses Them?


问:
Massive View Controller - IOS - Solutions
I'm sure every new iOS developer has the following problem: The View Controllers get very fast crowded with code for various purposes, easily getting to 500 + lines of code.

This is how it looks like for two basic and common screens:

1) The Form Screen:

2) The Table View Controller Screen

So far I have read about two different solutions:

First Solution: https://bendyworks.com/single-responsibility-principle-ios/.
This is based on Notifications, it completely separates the View Controller from the (Intentions) View Model and thus reduces code in the View Controller.
I think that it has the downside of breaking code, similar to Go-To structures.
It looks like this:

The second solution keeps the same crowded View Controllers (button actions are executed inside VC and so on). but uses libraries like TPKeyboardAvoiding, BlocksKit or other solutions most of them based on categories. With this second solution, code is drastically reduced but the view controller still has a lot of responsibility.

What do you think about these solutions? Which is better? Is there a better one?

答:
There's one special architecture they call VIPER (View, Interactor, Presenter, Entity and Routing). I'll try resume here what you need know:

View

they are dummy views;

contain objects like UIView, UIViewController, UILabel, etc;

waits the content from the Presenter;

handle user interaction and pass it to Presenter layer.

Presenter

doesn't know UI objects;

get inputs from View layer;

handle the view logic (add method will present other screen);

Routing

handle the navigation logic and transition animations;

knows objects like UINavigationController, UIWindow, etc;

So, what I think you will clean in your code:

data validations will move to Presenter layer;

navigation will move to Wireframe objects (Routing layer);

split your view controller observing DRY principle;

Complex screens will have two or more Views and Presenters.

You should see the follow link about VIPER architecture
http://mutualmobile.github.io/blog/2013/12/04/viper-introduction/

Good lucky!


问:
Qt/QML/C++ Application database connection object visibility
I am working on some Qt/QML/C++ app and I've got myself into some kind of dead end. Namely, this app uses mysql database and here is my questions: Is performance hurt if I instantate new database connection for every database query I need or is it better to connect to database at app startup via singleton object and reuse it?</p>

答:
Yes, performance will be impacted by creating a new connection every time - it's not a zero cost operation. However, is this a significant problem for your application? Only you can answer that after having done some profiling.

The answer to this is not to use a singleton though - at some point, your app is almost certainly going to want two simultaneous connections to the database. Look into using some sort of connection pool where you keep a set of connections around and reuse them as appropriate.


问:
Separate interface for mutation methods
I've been working on refactoring some code, and I think I may have taken the first step down the rabbit hole. I'm writing the example in Java, but I suppose it could be agnostic.

I have an interface Foo defined as

```<code>public interface Foo {

    int getX();

    int getY();

    int getZ();
}
</code>```

And an implementation as

```<code>public final class DefaultFoo implements Foo {

    public DefaultFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    private final int x;
    private final int y;
    private final int z;
}
</code>```

I also have an interface MutableFoo that provides matching mutators

```<code>/**
 * This class extends Foo, because a 'write-only' instance should not
 * be possible and a bit counter-intuitive.
 */
public interface MutableFoo extends Foo {

    void setX(int newX);

    void setY(int newY);

    void setZ(int newZ);
}
</code>```

There are a couple of implementations of MutableFoo that could exist (I haven't implemented them yet). One of them is

```<code>public final class DefaultMutableFoo implements MutableFoo {

    /**
     * A DefaultMutableFoo is not conceptually constructed
     * without all values being set.
     */
    public DefaultMutableFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public void setX(int newX) {
        this.x = newX;
    }

    public int getY() {
        return y;
    }

    public void setY(int newY) {
        this.y = newY;
    }

    public int getZ() {
        return z;
    }

    public void setZ(int newZ) {
        this.z = newZ;
    }

    private int x;
    private int y;
    private int z;
}
</code>```

The reason I have split these is because it is equally likely for each to be used. Meaning, it is equally likely that someone using these classes will want an immutable instance, as it is they will want a mutable one.

The primary use-case that I have is an interface called StatSet that represents certain combat details for a game (hitpoints, attack, defense). However, the "effective" stats, or the actual stats, are a result of the base stats, that can never be changed, and the trained stats, which can be increased. These two are related by

```<code>/**
 * The EffectiveStats can never be modified independently of either the baseStats
 * or trained stats. As such, this StatSet must never provide mutators.
 */
public StatSet calculateEffectiveStats() {
    int effectiveHitpoints =
        baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    int effectiveAttack =
        baseStats.getAttack() + (trainedStats.getAttack() / 4);
    int effectiveDefense =
        baseStats.getDefense() + (trainedStats.getDefense() / 4);

    return StatSetFactory.createImmutableStatSet(effectiveHitpoints, effectiveAttack, effectiveDefense);
}
</code>```

the trainedStats are increased after every battle like

```<code>public void grantExperience() {
    int hitpointsReward = 0;
    int attackReward = 0;
    int defenseReward = 0;

    final StatSet enemyStats = enemy.getEffectiveStats();
    final StatSet currentStats = player.getEffectiveStats();
    if (enemyStats.getHitpoints() >= currentStats.getHitpoints()) {
        hitpointsReward++;
    }
    if (enemyStats.getAttack() >= currentStats.getAttack()) {
        attackReward++;
    }
    if (enemyStats.getDefense() >= currentStats.getDefense()) {
        defenseReward++;
    }

    final MutableStatSet trainedStats = player.getTrainedStats();
    trainedStats.increaseHitpoints(hitpointsReward);
    trainedStats.increaseAttack(attackReward);
    trainedStats.increaseDefense(defenseReward);
}
</code>```

but they aren't increased just after battle. Using certain items, employing certain tactics, clever use of the battlefield all can grant different experience.

Now for my questions:

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

Is splitting them in this way the 'right' approach if they are equally likely to be used, or is there a different, more accepted pattern that I should use instead (eg. Foo foo = FooFactory.createImmutableFoo(); which could return DefaultFoo or DefaultMutableFoo but is hidden because createImmutableFoo returns Foo)?

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

The reason I started designing it this way is because I'm of the mindset that all implementers of an interface should adhere to the simplest interface possible, and provide nothing more. By adding setters to the interface, now the effective stats can be modified independently of its parts.

Making a new class for the EffectiveStatSet does not make much sense as we're not extending the functionality in any way. We could change the implementation, and make an EffectiveStatSet a composite of two different StatSets, but I feel that is not the right solution;

```<code>public class EffectiveStatSet implements StatSet {

    public EffectiveStatSet(StatSet baseStats, StatSet trainedStats) {
        // ...
    }

    public int getHitpoints() {
        return baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    }
}
</code>```

答:
The separation of a mutable collection interface and a read-only-contract collection interface is an example of interface segregation principle. I don't think there is any special names given to each application of principle.

Notice a few words here: "read-only-contract" and "collection".

A read-only-contract means that class A gives class B a read-only access, but does not imply that the underlying collection object is actually immutable. Immutable means that it shall never change in the future, no matter by any agent. A read-only-contract only says that the recipient is not allowed to change it; someone else (in particular, class A) is allowed to change it.

To make an object immutable, it must be truly immutable - it must deny attempts to change its data regardless of the agent requesting it.

The pattern is most likely observed on objects that represents a collection of data - lists, sequences, files (streams), etc.

The word "immutable" becomes fad, but the concept is not new. And there are many ways of using immutability, as well as many ways of achieving better design using something else (i.e. its competitors).

Here is my approach (not based on immutability).

Define a DTO (data transfer object), also known as a value tuple.

This DTO will contain the three fields: hitpoints, attack, defense.

Just fields: public, anyone can write, no protection.

However, a DTO must be a throwaway object: if class A needs to pass a DTO to class B, it makes a copy of it and pass the copy instead. So, B can use the DTO however it likes (writing to it), without affecting the DTO that A holds on to.

The grantExperience function to be broken down into two:

calculateNewStats

increaseStats

calculateNewStats will take the inputs from two DTO, one representing the player stats and another representing the enemy stats, and perform the calculations.

For the input, the caller should choose among the base, trained or effective stats, according to your needs.

The result will be a new DTO where each field (hitpoints, attack, defense) stores the amount to be incremented for that ability.

The new "amount to increment" DTO does not concern about the upper limit (imposed maximum cap) for those values.

increaseStats is a method on the player (not on the DTO) that takes an "amount to increment" DTO, and applies that increment on the DTO that is owned by the player and represents the player's trainable DTO.

If there are applicable maximum values for these stats, they are enforced here.

In case calculateNewStats is found to not depend on any other player or enemy information (beyond the values in the two input DTO), this method can potentially be located anywhere in the project.

If the calculateNewStats is found to have a full dependency on the player and enemy objects (that is, future player and enemy objects may have new properties, and calculateNewStats must be updated to consume as much of their new properties as possible), then calculateNewStats must accept those two objects, not merely the DTO. However, its calculation result will still be the increment DTO, or whatever simple data-transfer objects that carries the information that is used to perform an increment/upgrade.

Title: Separate interface for mutation methods


问:
How to make a large codebase easier to understand
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?

答:
The most important rule I have found for making it easier for new developers to understand a codebase is perfect agreement is expensive.

If new developers must perfectly understand the system they are working on, it prevents all opportunities for on the job learning.  I think the programmer's notes are an excellent start, but I would go further.  Try to write code that, if approached anew, would allow a developer to figure out what they are doing on the fly, rather than requiring them to learn before they do.  Little things like asserts for cases you know can never occur, along with comments explaining why the assert is valid, go a long way.  So does writing code which fails gracefully rather than segfaulting if you do anything wrong.

ContentLicense: CC BY-SA 4.0


答:
Undefined behavior is used in situations where it is not feasible for the spec to specify the behavior, and it has always been written to allow absolutely any behavior possible.

The extremely ultra-loose rules for UB are helpful when you think about what a spec conforming compiler must go through.  You may have sufficient compiling horsepower to emit an error when you do some bad UB in one case, but add a few layers of recursion and now the best you can do is a warning.  The spec has no concept of "warnings," so if the spec had given a behavior, it would have to be "an error."

The reason we see more and more side effects of this is the push for optimization.  Writing a spec conforming optimizer is hard.  Writing a spec conforming optimizer which also happens to do a remarkably good job guessing what you intended when you went outside the spec is brutal.  It is much easier on the compilers if they get to assume UB means UB.

This is especially true for gcc, which tries to support many many instruction sets with the same compiler.  It is far easier to let UB yield UB behaviors than it is to try to grapple with all the ways every single UB code could go wrong on every platform, and factor it into the early phrases of the optimizer.

Title: When did Undefined Behavior in C jump the causality barrier

Body:
Some hyper-modern C compilers will infer that if a program will invoke Undefined Behavior when given certain inputs, such inputs will never be received.  Consequently, any code which would be irrelevant unless such inputs are received may be eliminated.

As a simple example, given:

```<code>void foo(uint32_t);

uint32_t rotateleft(uint_t value, uint32_t amount)
{
  return (value << amount) | (value >> (32-amount));
}

uint32_t blah(uint32_t x, uint32_t y)
{
  if (y != 0) foo(y);
  return rotateleft(x,y);
}
</code>```

a compiler may infer that because evaluation of value >> (32-amount) will yield Undefined Behavior when amount is zero, function blah will never be called with y equal to zero; the call to foo can thus be made unconditional.

From what I can tell, this philosophy seems to have caught hold sometime around 2010.  The earliest evidence I've seen of its roots goes back to 2009, and it's been enshrined in the C11 standard which explicitly states that if Undefined Behavior occurs at any point in a program's execution, the behavior of the entire program retroactively becomes undefined.

Was the notion that compilers should attempt to use Undefined Behavior to justify reverse-causal optimizations (i.e. the Undefined Behavior in the rotateleft function should cause the compiler to assume that blah must have been called with a non-zero y, whether or not anything would ever cause y to hold a non-zero value) seriously advocated prior to 2009?  When was such a thing first seriously proposed as an optimization technique?

[Addendum]

Some compilers have, even in the 20th Century, included options to enable certain kinds of inferences about loops and the values computed therein.  For example, given

```<code>int i; int total=0;
for (i=n; i>=0; i--)
{
  doSomething();
  total += i*1000;
}
</code>```

a compiler, even without the optional inferences, might rewrite it as:

```<code>int i; int total=0; int x1000;
for (i=n, x1000=n*1000; i>0; i--, x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

since the behavior of that code would precisely match the original, even if the compiler specified that int values always wrap in mod-65536 two's-complement fashion.  The additional-inference option would let the compiler recognize that since i and x1000 should cross zero at the same time, the former variable can be eliminated:

```<code>int total=0; int x1000;
for (x1000=n*1000; x1000 > 0; x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

On a system where int values wrapped mod 65536, an attempt to run either of the first two loops with n equal to 33 would result in doSomething() being invoked 33 times.  The last loop, by contrast, wouldn't invoke doSomething() at all, even though the first invocation of doSomething() would have preceded any arithmetic overflow.  Such a behavior might be considered "non-causal", but the effects are reasonably well constrained and there many cases where the behavior would be demonstrably harmless (in cases where a function is required to yield some value when given any input, but the value may be arbitrary if the input is invalid, having the loop finish faster when given an invalid value of n would actually be beneficial).  Further, compiler documentation tended to be apologetic for the fact that it would change the behavior of any programs--even those that engaged in UB.

I'm interested in when compiler writers' attitudes changed away from the idea that platforms should when practical document some usable behavioral constraints even in cases not mandated by the Standard, to the idea that any constructs which would rely upon any behaviors not mandated by the Standard should be branded illegitimate even if on most existing compilers it would work as well or better than any strictly-compliant code meeting the same requirements (often allowing optimizations which would not be possible in strictly-compliant code).


答:
To me it seems you have a solution looking for a problem.

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

This might be a little provoking, but actually I would call it "overdesigning things" or "overcomplicating things". By offering a mutable and an immutable variant of the same class, you offer two functionally equivalent solutions for the same problem, which differ only in non-functional aspects like performance behaviour, API and security against side effects. I guess that is because you fear to make a decision which one to prefer, or because you try to implement the "const" feature of C++ in C#. I guess in 99% of all cases it will not make a big difference if the user picks the mutable or the immutable variant, he can solve his problems with the either or the other. Thus "likeliness of a class to be used" is probably result of what you offer in your library - if you offer two almost similar solutions to the same problem, expect a 50% chance that the users will pick variant A or B. If you offer just one solution, the likeliness is high they will use that solution, and will be happy with it.

The exception is when you design a new programming language or a multi purpose framework which is going to be used by some ten thousands of programmers or more. Then it can indeed scale better when you offer immutable and mutable variants of general purpose data types. But this is a situation where you will have thousands of different usage scenarios - which is probably not the problem you face, I guess?

Is splitting them in this way the 'right' approach if they are equally likely to be used or is there a different, more accepted pattern

The "more accepted pattern" is called KISS - keep it simple and stupid. Make a decision for or against mutability for the specific class/interface in your library. For example, if your "StatSet" has a dozen of attributes or more, and they are mostly changed individually, I would prefer the mutable variant and just not modify the base stats where they should not be modified. For something like a Fooclass with attributes X,Y,Z (a three dimensional vector), I would probably prefer the immutable variant.

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

Overcomplicated designs make software harder to test, harder to maintain, harder to evolve.

Title: Separate interface for mutation methods

Body:
I've been working on refactoring some code, and I think I may have taken the first step down the rabbit hole. I'm writing the example in Java, but I suppose it could be agnostic.

I have an interface Foo defined as

```<code>public interface Foo {

    int getX();

    int getY();

    int getZ();
}
</code>```

And an implementation as

```<code>public final class DefaultFoo implements Foo {

    public DefaultFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public int getY() {
        return y;
    }

    public int getZ() {
        return z;
    }

    private final int x;
    private final int y;
    private final int z;
}
</code>```

I also have an interface MutableFoo that provides matching mutators

```<code>/**
 * This class extends Foo, because a 'write-only' instance should not
 * be possible and a bit counter-intuitive.
 */
public interface MutableFoo extends Foo {

    void setX(int newX);

    void setY(int newY);

    void setZ(int newZ);
}
</code>```

There are a couple of implementations of MutableFoo that could exist (I haven't implemented them yet). One of them is

```<code>public final class DefaultMutableFoo implements MutableFoo {

    /**
     * A DefaultMutableFoo is not conceptually constructed
     * without all values being set.
     */
    public DefaultMutableFoo(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public int getX() {
        return x;
    }

    public void setX(int newX) {
        this.x = newX;
    }

    public int getY() {
        return y;
    }

    public void setY(int newY) {
        this.y = newY;
    }

    public int getZ() {
        return z;
    }

    public void setZ(int newZ) {
        this.z = newZ;
    }

    private int x;
    private int y;
    private int z;
}
</code>```

The reason I have split these is because it is equally likely for each to be used. Meaning, it is equally likely that someone using these classes will want an immutable instance, as it is they will want a mutable one.

The primary use-case that I have is an interface called StatSet that represents certain combat details for a game (hitpoints, attack, defense). However, the "effective" stats, or the actual stats, are a result of the base stats, that can never be changed, and the trained stats, which can be increased. These two are related by

```<code>/**
 * The EffectiveStats can never be modified independently of either the baseStats
 * or trained stats. As such, this StatSet must never provide mutators.
 */
public StatSet calculateEffectiveStats() {
    int effectiveHitpoints =
        baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    int effectiveAttack =
        baseStats.getAttack() + (trainedStats.getAttack() / 4);
    int effectiveDefense =
        baseStats.getDefense() + (trainedStats.getDefense() / 4);

    return StatSetFactory.createImmutableStatSet(effectiveHitpoints, effectiveAttack, effectiveDefense);
}
</code>```

the trainedStats are increased after every battle like

```<code>public void grantExperience() {
    int hitpointsReward = 0;
    int attackReward = 0;
    int defenseReward = 0;

    final StatSet enemyStats = enemy.getEffectiveStats();
    final StatSet currentStats = player.getEffectiveStats();
    if (enemyStats.getHitpoints() >= currentStats.getHitpoints()) {
        hitpointsReward++;
    }
    if (enemyStats.getAttack() >= currentStats.getAttack()) {
        attackReward++;
    }
    if (enemyStats.getDefense() >= currentStats.getDefense()) {
        defenseReward++;
    }

    final MutableStatSet trainedStats = player.getTrainedStats();
    trainedStats.increaseHitpoints(hitpointsReward);
    trainedStats.increaseAttack(attackReward);
    trainedStats.increaseDefense(defenseReward);
}
</code>```

but they aren't increased just after battle. Using certain items, employing certain tactics, clever use of the battlefield all can grant different experience.

Now for my questions:

Is there a name for splitting interfaces by accessors and mutators into separate interfaces?

Is splitting them in this way the 'right' approach if they are equally likely to be used, or is there a different, more accepted pattern that I should use instead (eg. Foo foo = FooFactory.createImmutableFoo(); which could return DefaultFoo or DefaultMutableFoo but is hidden because createImmutableFoo returns Foo)?

Are there any immediately foreseeable downsides to using this pattern, save for complicating the interface hierarchy?

The reason I started designing it this way is because I'm of the mindset that all implementers of an interface should adhere to the simplest interface possible, and provide nothing more. By adding setters to the interface, now the effective stats can be modified independently of its parts.

Making a new class for the EffectiveStatSet does not make much sense as we're not extending the functionality in any way. We could change the implementation, and make an EffectiveStatSet a composite of two different StatSets, but I feel that is not the right solution;

```<code>public class EffectiveStatSet implements StatSet {

    public EffectiveStatSet(StatSet baseStats, StatSet trainedStats) {
        // ...
    }

    public int getHitpoints() {
        return baseStats.getHitpoints() + (trainedStats.getHitpoints() / 4);
    }
}
</code>```


答:
I miss my whiteboard.

We used to be in a small room with a small 3-4 person team, a whiteboard and a door.  Some of our best designs were created on that whiteboard.

Then they moved us into an open plan area with no privacy, no whiteboard and too much noise.  Surprise, surprise productivity and morale has dropped  :-(

Title: White Boards -- Who Uses Them?

Body:
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!


问:
Is there a key/key lookup table type provided in .NET?
It seems like a pretty straightforward thing to add, but I just want to be sure .NET doesn't already provide one and save me from adding unnecessary code:

I need a lookup table (like a Dictionary) that instead using a key/value pair, uses the first key to find the second key, and vice versa. For example -

```<code>theList.Add("foo", "bar");
x = theList["foo"]; // Returns "bar"
y = theList["bar"]; // Returns "foo"
</code>```

Thanks in advance!

答:
There is no such datatype, probably because this is a very special requirement which can be easily solved by utilizing a dictionary and adding simply both pairs

```<code> theDictionary.Add("foo", "bar");
 theDictionary.Add("bar", "foo");
</code>```

Obviously, you can put this into a generic function like

```<code>void MyDictAdd(Dictionary<T,T> dict, T key1, T key2)
{
    dict.Add(key1,key2);
    dict.Add(key2,key1);
}
</code>```

Body:
There is no such datatype, probably because this is a very special requirement which can be easily solved by utilizing a dictionary and adding simply both pairs

 theDictionary.Add("foo", "bar");
 theDictionary.Add("bar", "foo");

Obviously, you can put this into a generic function like

void MyDictAdd(Dictionary<T,T> dict, T key1, T key2)
{
    dict.Add(key1,key2);
    dict.Add(key2,key1);
}


答:
Another possibility would be to create a method which would search both keys and values. Also this would and more complexity to the mix O(n) for the search. But would reduce memory usage.</p>

```<code>string GetValue(string search, Dictionary<string, string> dictionary) {
    foreach(var pair in dictionary)
    {
        if (pair.Key == search) {
            return pair.Value;
        }
        else if (pair.Value == search) {
            return pair.Key;
        }
    }
    return null;
}
</code>```

Title: Is there a key/key lookup table type provided in .NET?

Body:
It seems like a pretty straightforward thing to add, but I just want to be sure .NET doesn't already provide one and save me from adding unnecessary code:

I need a lookup table (like a Dictionary) that instead using a key/value pair, uses the first key to find the second key, and vice versa. For example -

```<code>theList.Add("foo", "bar");
x = theList["foo"]; // Returns "bar"
y = theList["bar"]; // Returns "foo"
</code>```

Thanks in advance!

Body:
Another possibility would be to create a method which would search both keys and values. Also this would and more complexity to the mix O(n) for the search. But would reduce memory usage.

string GetValue(string search, Dictionary<string, string> dictionary) {
    foreach(var pair in dictionary)
    {
        if (pair.Key == search) {
            return pair.Value;
        }
        else if (pair.Value == search) {
            return pair.Key;
        }
    }
    return null;
}


问:
Integer conversion with Console.ReadLine()
To read an integer from user input, you can use:

```<code>int number = Convert.ToInt32(Console.ReadLine());
</code>```

But why won't the following work?

```<code>int number = (int) Console.ReadLine();
</code>```

What's the difference between Convert.ToInt32 and casting with (int)?

答: That is because no explicit or implicit conversion exists between those two types in .NET framework. In other words explicit conversion operator is not overloaded in string class. More on converting strings to numbers in C# is in this article. Also read about casting.</p>


答:
It has always been the case in C and C++ that as a result of undefined behaviour, anything can happen. Therefore it has also always been the case that a compiler can make the assumption that your code doesn't invoke undefined behaviour: Either there is no undefined behaviour in your code, then the assumption was correct. Or there is undefined behaviour in your code, then whatever happens as a result of the incorrect assumption is covered by "anything can happen".

If you look at the "restrict" feature in C, the whole point of the feature is that the compiler can assume there is no undefined behaviour, so there we reached the point where the compiler not only may but actually should assume there is no undefined behaviour.

In the example that you give, the assembler instructions usually used on x86 based computers to implement left or right shift will shift by 0 bits if the shift count is 32 for 32 bit code or 64 for 64 bit code. This will in most practical cases lead to undesirable results (and results that are not the same as on ARM or PowerPC, for example), so the compiler is quite justified to assume that this kind of undefined behaviour doesn't happen. You could change your code to

```<code>uint32_t rotateleft(uint_t value, uint32_t amount)
{
   return amount == 0 ? value : (value << amount) | (value >> (32-amount));
}
</code>```

and suggest to the gcc or Clang developers that on most processors the "amount == 0" code should be removed by the compiler, because the assembler code generated for the shift code will produce the same result as value when amount == 0.

Body:
It has always been the case in C and C++ that as a result of undefined behaviour, anything can happen. Therefore it has also always been the case that a compiler can make the assumption that your code doesn't invoke undefined behaviour: Either there is no undefined behaviour in your code, then the assumption was correct. Or there is undefined behaviour in your code, then whatever happens as a result of the incorrect assumption is covered by "anything can happen".

If you look at the "restrict" feature in C, the whole point of the feature is that the compiler can assume there is no undefined behaviour, so there we reached the point where the compiler not only may but actually should assume there is no undefined behaviour.

In the example that you give, the assembler instructions usually used on x86 based computers to implement left or right shift will shift by 0 bits if the shift count is 32 for 32 bit code or 64 for 64 bit code. This will in most practical cases lead to undesirable results (and results that are not the same as on ARM or PowerPC, for example), so the compiler is quite justified to assume that this kind of undefined behaviour doesn't happen. You could change your code to

uint32_t rotateleft(uint_t value, uint32_t amount)
{
   return amount == 0 ? value : (value << amount) | (value >> (32-amount));
}

and suggest to the gcc or Clang developers that on most processors the "amount == 0" code should be removed by the compiler, because the assembler code generated for the shift code will produce the same result as value when amount == 0.


答:
I would not agree this is a very good approach, mainly due to

When you refactor your project, move methods around, the documentation breaks.

If documentation is not properly updated, it will result in more confusion than help understanding the code.

If you have unit tests for each method/ integration tests for each module, it would be a self documentation more maintainable and easier to understand compared to code comments.

Yes, having a proper directory structure definitely going to help.

Title: How to make a large codebase easier to understand

Body:
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?


答:
Consider using a queue, where each method access resulting an entry, and use a

timer job

queue length reaching certain threshold

to flush the queue into the database.

Title: Good practice to save the last time user accessed the app

Body:
Using a JWT authentication, the user doesn't have to log in each time he uses my app.

I would like to save in DB the last time the user used/opened the app.

Technically, I have a set of REST API that could audit each request and save in database the timestamp corresponding to the current user access but ... for each request?!

What is a good practice to store this information without involving database each time the user makes a request?


问:
Regex backtracking on simple pattern
I've got this code in Mathematica that fetches the left or right side of an equation by turning it into pure text then textually getting rid of the other side through regex. I've isolated the faulty pattern and can't understand why it is producing "infinite" backtracking:

```<code>(\S+\s*)+(==|>=|<=|>|<)\s*
</code>```

sample text:

```<code>x <= func[abcde,1]
</code>```

I almost thought it was because of the brackets describing some weird, unwanted character set, but whatever characters I substitute with the brackets:

```<code>x <= func:abcde,1:
</code>```

It still infinitely backtracks. The only way out is if "abcde" is shortened to only 4 characters "bcde", "abcd", "cbde"...

I don't get it. What else is to backtrack? <= matches and that pretty much fixes everything to that point...

答:
With the caveat that behaviour may vary by regex engine (which are you using?), one thought:

(\S+\s*)+ (the first half) also matches strings matched by (==|>=|<=|>|<)\s* (the second half).  Matching is greedy by default, so the first half will swallow the operator, then the second half will fail, then backtracking will begin.  If you can use non-greedy matching or tighten up \S to exclude the operators, things should work more reliably.

As for the five vs. four characters, I don't know but am guessing it has to do with how your regex engine builds or optimizes its automata.

Title: Regex backtracking on simple pattern


答:
For complex systems it may be worth it to not just document each file, but their interactions and hierarchy, and how the program structures and why.

For example a game engine is usually quite complex and its hard to decide what calls what after hundred layers of abstraction. It may be worth creating a file like "Architecture.txt" to explain how and why is the code structured like this, and why there is that pointless looking abstraction layer there.


答:
There is no way to cast a System.String to a System.Int32

Unlike many other languages (e.g. PHP or JavaScript), C# is strongly typed. This means numbers (int in your case), and strings are two very different things. One cannot be cast to the other, because the C# compiler has no idea of how to make an implicit conversion between the two types. In a loosly typed language there are no real types, the compiler usually makes an educated guess about which type your variable has.

So, casting is for when you have a type that "may be" another type. You may for instance have an integer boxed as an object. In this case it is perfectly legal to write int number = (int)someObject; but you need to know beforehand that someObject can be cast to an integer, otherwise an InvalidCastException will be thrown at runtime.

You can also "cast" a type to (one of) its base-type(s), this commonly referred to as down-casting. For example: var enumerable = (IEnumerable<string>)new List<string>();. This however, is usually done implicitly in method calls, there are no common use-cases where you explicitly have to down-cast a type.

It's important to note that down-casting will not "convert" a type. My variable named enumerable in the above example is still a List<string>. The difference is that it is now boxed as a IEnumerable<string>. You can unbox your list via a new cast: var list = (List<string>)enumerable; or via the as-keyword if you are using a reference-type (class).

C# also supports casting between the different number types. For instance a System.Decimal or a System.Double can be cast to a System.Int32. But the decimals will get truncated. For instance int truncatedPI = (int)Math.PI; will give you 3. But as far as i know; this is just compiler-magic.

What you need to look into is something called parsing.

Parsing is the mechanism in which you have a value, that is not in the desired type (commonly a string) and parse it to the type you want, either by using a built-in parser or by writing your own parser.

Most of the common value-types (structs and enums) in .NET have built-in static Parse-methods.

For integers: int.Parse("15"), for dates: DateTime.Parse("2015-08-02 00:00") and so on. These are built-in parsers, which are included in the .NET framework.

Console.ReadLine returns a string which cannot be implicitly converted to a integer by casting (boxing or unboxing). To solve your problem you need to use one of the parsing-methods mentioned above.

In your case int number = int.Parse(Console.ReadLine()); would most likely suffice. But be careful, if you enter something like "HELLO" in your console-application, int.Parse will throw a FormatException since what you have entered cannot be interpreted by the parser.

This is where TryParse and TryParseExact, come in. They are usually more viable alternatives for handling user input.

As a general rule — try to avoid Convert.To[Type] when parsing strings. These are generally just "lazy" implementations of the Parse method anyways. Using the parsing methods mentioned above comes with more options, better scalability and also prompts the programmer with more precise information of what is going on in your code.

Title: Integer conversion with Console.ReadLine()

Body:
To read an integer from user input, you can use:

```<code>int number = Convert.ToInt32(Console.ReadLine());
</code>```

But why won't the following work?

```<code>int number = (int) Console.ReadLine();
</code>```

What's the difference between Convert.ToInt32 and casting with (int)?


问:
"CSS first" vs "HTML first" (Bootstrap, SASS)
Kind of a follow-up to Should I write HTML or CSS first?

On a relatively large website, we are considering to use SASS and/or Bootstrap.
From previous projects, there seem to be different ways to go about it:

A framework (e.g. bootstrap) provides a bunch of css classes (esp for the grid layout). We may even add to that with our own reusable classes. We then create the html to use these classes.

If we want to change the layout, we have to modify the HTML, not the CSS. A class for a sidebar would be like col-lg-3 instead of sidebar-left.

I call this the "CSS first" strategy.

We first create our HTML, using semantic classes. A sidebar would be classed sidebar-left, or even sidebar-first to not imply anything about how it will be displayed. Then we use custom CSS that targets this region.

Probably using a SASS mixin for the grid column layout.

If we want to change the layout (e.g. make the sidebar smaller), we modify the CSS, not the HTML.

I call this the "HTML first" strategy.

Usually we want to do this with "components", where parts of the page are independent of each other, and we avoid arbitrary deep selectors.

Traditionally in Drupal (this is what we work with), a lot of the HTML is already provided by core and 3rd party modules. Traditionally, we would leave most of the HTML as it is, and then target it with ugly deeply nested selectors.

This is also "HTML first", but without components. I try to avoid this pattern.

Often the classes provided in the generated html are based on configuration living in the database, and created with the UI. So then we have CSS (=code) depending on stuff in the database. It would be more maintainable in the other direction, if stuff in the database depends on CSS.

Content authors want to be able to add some special effects in their authored html (which is filtered, of course). E.g. wrapper boxes for images. We provide some classes that they can use.

This would fall into the "CSS first" strategy, although it is a special use case.

In a CMS, we might have some components that you can choose from the UI, to configure how something should be displayed. These components might have human names that show how it looks like, e.g. "slider", "grid", "blue box".

Maybe this is again "CSS first".

The strategies 1. and 2. seem quite opposite to each other. I can think of examples where one or the other approach would be preferable. But I wonder if there are some general rules of thumb which approach is better, or where to use which.

It seems a main difference is whether I prefer to update the HTML or the CSS, if I want to make a layout / appearance change.

This also leads to the question of how "semantic" your class names should be.

With the "CSS first" approach, I would write CSS for a class "shiny-blue-button" and another "shiny-red-button". If I want to change the appearance, I will change the HTML to use the red button instead of the blue one.

With the "HTML first" approach, I would write HTML with a class "panic-button" and another "submit-button", and then style them accordingly. Here the classes are way more semantic, but much less reusable.

See also Cogent arguments for 'semantic css' over 'object oriented css'

答:
Your 'HTML' represents the elements that corresponds to the DOM. As your CSS is applied to these elements to create the layer of presentation, it would be like coloring before sketching. I would use HTML to define the individual elements of page, without style first. When their behavior works to pass the testing, I would start using CSS. The behavior usually asks for a dynamical use of classes - like :hover or a certain state or theme.

To answer your question: define HTML before CSS, in my opinion.


问:
When to use Prototypes & the correct usage of Prototypes ( Javascript )
I have been programming in Javascript for a while and I am quite comfortable with it. And I know the basic concept of prototypes and I have also used them a few times. But one thing I can't figure out is that when should a prototype be used.

And what is the correct usage of prototypes. For example:

Currently I am creating a Task Management system. Within this system you can create Projects, each project can then have multiple tasks added into it. Currently I have created the functionality of creating projects.

All user projects are saved into a Array in my MongoDB database. Once a user creates a project it is added into the projects array. After that I created a getProjects function. This functions uses a GET request and retrieves all the projects for the logged-in user. Once the data is retrieved I save the projects array into an angular variable:

CREATE Projects:

```<code>  // Create Project Function
 $scope.createProject = function(id){
    var pTitle = document.getElementById("pojectTitle").value;
    console.log("Entered create Project fucntion");
    console.log("user id is" + id);
    console.log(pTitle);

    // Simple POST request example (passing data) :
    $http.post("/createProject/"+ id +"", {
        projectTitle: pTitle,
        userID      : id
    }).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.getProjects();
        console.log("project created");
        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
 };
</code>```

GET Projects:

```<code>$scope.getProjects = function(id) {
   console.log("getting user projects, please wait ......");
   // Simple GET request example (passing data) :
   $http.get("/user/projects/" + id + "", {

   }).
   success(function(data, status, headers, config) {
       // this callback will be called asynchronously
       // when the response is available

       $scope.userProjects = data;
       console.log("user projects are here " + $scope.userProjects);

   }).
   error(function(data, status, headers, config) {
       // called asynchronously if an error occurs
       // or server returns response with an error status.
   });

 };
</code>```

All the returning JSON data from the above request is saved in:

```<code>   $scope.userProjects = [];
</code>```

Currently I am using angular's ng-repeat in my HTML file to loop through the userProjects array and create a Div for each project in the array (within ng-repeat). And in the centre of the div writer the name of the project. See below:

Now here is my question

I want to make each div "Clickable" to when a user clicks on the div they are directed to another page where they can add tasks within the project.

I thought about using Prototype functionality to attach links to each div. So my thought was that I would create Projects class in my angular controller and while I loop through the project array that was returned from the GET request, for each project in the array I will create an instance (object) of that class and attached a clickable event to each div.

Is this a good approach?
Is this a good use of prototype?
Should I even be using prototypes?
If not, what recommendations could you make?

If you need more information to answer the question please let  me know.

Thanks in advance.

答:
The correct usage of prototypes in JavaScript depends on what you want to achieve. The understanding of what a prototype is and why it exists is a very good question.

Prototype exists in JavaScript, because objects do not have classical inheritance based on a Class, like in traditional languages. In JavaScript, objects are pairs of keys and values. They have one additional property: a pointer to another object: the object prototype. Important to know is that every function is a first-class object in JavaScript.

Prototype is used primarily for inheritance; you add methods and properties on a function’s prototype to make methods and properties available to its instances. Every object inherits properties from an object, and is the object’s parent. This makes the prototype property work like a class property - all instances deriving from the same parent class have access to this property.

If you do not use the property, it will be a static property, which bound to that particular type of instance without inheritance.

So, when to use prototypes? Prototypes are for optimization. As you are thinking in objects and you want shared attributes for a specific problem domain, this is a good reason to use the prototype property to implement this.


问:
Introducing Pull Requests for a 2 person team - merge my own requests?
I'm introducing git to a junior team member (a co-op).

They are comfortable now with the basics of adding, committing, pushing and pulling.

Now I want to introduce them to pull requests and branches.

If they start doing pull requests in branches, should I do the same for my on-going work?

I will be the one merging their pull requests in.  I wasn't sure if it would make the most sense for me to work in branches (generally a good practice I know but I am curious about this specific situation of 2 devs with one junior) and if so does that mean that I'll just be merging my own branches into master.  Would I even do a pull request for my work / branches anyway?  Generally we use the basic github Feature Branch Workflow for these changes:

https://www.atlassian.com/git/tutorials/comparing-workflows/feature-branch-workflow

Is there a purpose for using pull requests on my own repo if I am the only developer? is useful but not quite as specific.

Whats the work flow with 2 people on a project also seems more general

and

Should I open pull requests from a branch on the official repo or my fork? seems more about forks.

答:
No. You should not merge your own pull requests. What's good for the goose is good for the gander. Merging your own pull requests sets a bad precedent for our junior dev. It also means that no one else is looking at your code. No matter how senior we may be, we all makes mistakes and write bad code from time to time. Teach your junior how code reviews work from the other side by making him review and merge your work.

He may not have the same eye you do, but it will get him accustomed to the process from the reviewer's end and he may surprise you and catch something stupid you did. Minimally, it will give you an indication of pieces of code that are obvious to you, that aren't obvious to him. This has a two fold benefit.

You both learn where your junior needs to focus learning activities.

You learn where you're being more clever than you should be.


问:
Accepted Patterns For Base Class with both Static And User-Defined Data Sources
I have a requirement to build a 'base' profile library (in C# - NET 4.5.2) for various different internal (technical) consumers. This profile consists of metadata fields that would be shared by a wide-variety of different profile implementations. The metadata for these different profiles is stored in a single location but each actual implementation for the base profile will have it's own data storage (which I'll know nothing about).

Rather than provide an actual service we will only be providing the base classes / interfaces necessary to allow developers to implement their own profile services.

Ideally, I'd like to make the hydration of the base profile's metadata fields completely automatic for developers - they focus on hydrating their own fields in their child class only.

My requirements are:

Base profile all other profile objects must inherit

Base profile self-hydrates from a static data source that is opaque to implementors.

The ability to query for many profiles based on a predicate, a profile ID list, or both.

CRUD operations for a given profile that permit said operations on the base profile metadata in addition to whatever the user needs to do in their own system(s).

On idea that has been floated already includes allowing developers to provide a generator function (Func<Guid, Profile<T>>) where Guid is the Id of the profile (for existing reads) and the function executes whatever logic the developer requires to initialize their profile while at the same time getting the base profile data.

I'd be curious to hear the communities thoughts on this though (and whether or not this is even a good course to chart).

答:
I recently made an implementation of the ASP.NET 5 Identity-framework which was a pain in the butt, it has its UserStore (and RoleStore) which is kind of annoying to implement.

My implementation can be found here, it might give you a few ideas!

This sounds sort of like the same thing. You need a base class where different type of profiles(?) can be stored, but only abstract methods for getting/setting these profiles. I kind of enjoy the pattern that the Identity base-classes provides, even though it's kind of annoying to implement, because it gives the implementer full freedom of what data-store (s)he wants to use.

From what i can tell from your question, each profile must have an Id which must be a System.Guid.

So why not start with an interface containing only this?

```<code>public interface IProfile
{
    Guid Id { get; }
}
</code>```

Then why not implement a Store for the IProfile, such as in Identity

```<code>public abstract class ProfileStore<TProfile>
    where TProfile : class, IProfile
{
    public abstract Task<TProfile> FindByIdAsync(Guid profileId);
    public abstract Task<IEnumerable<TProfile>> FindManyAsync(Expression<Func<TProfile, bool>> query);
    public abstract Task SaveProfileAsync(TProfile profile);
}
</code>```

You might (of course) want to add more methods of getting or saving your profiles.

All profile stores could then be added to some sort of ProfileStoreCollection where you can self-hydrate all stores by iterating over them, and invoking the InsertAsync-method.

This should be sufficient for what you are asking, please comment if i have missed some vital part!

Here is an example implementation (Using MongoDB and its latest driver):

A profile:

```<code>public class SomeProfile : IProfile
{
    [BsonId]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public DateTime Expires { get; set; }
}
</code>```

The store:

```<code>public class MongoDBProfileStore : ProfileStore<SomeProfile>
{
    private IMongoCollection<SomeProfile> _profileCollection;

    public MongoDBProfileStore(IMongoCollection<SomeProfile> profileCollection)
    {
        _profileCollection = profileCollection;
    }

    public override async Task<SomeProfile> FindByIdAsync(Guid profileId)
    {
        var filter = Builders<SomeProfile>.Filter
            .Eq(nameof(SomeProfile.Id), profileId);
        // the nameof-keyword is new in C#6 (returns "Id")

        var profiles = await _profileCollection.FindAsync(filter);
        await profiles.MoveNextAsync();

        if (profiles.Current != null)
        {
            return profiles.Current.FirstOrDefault();
        }
        return null;
    }

    public override async Task<IEnumerable<SomeProfile>> FindManyAsync(Expression<Func<SomeProfile, bool>> query)
    {
        var profiles = await _profileCollection.FindAsync(query);

        await profiles.MoveNextAsync();

        if (profiles.Current != null)
        {
            return profiles.Current.ToList();
        }
        return null;
    }

    public override async Task SaveProfileAsync(SomeProfile profile)
    {
        await _profileCollection.InsertOneAsync(profile);
    }
}
</code>```

Body:
I recently made an implementation of the ASP.NET 5 Identity-framework which was a pain in the butt, it has its UserStore (and RoleStore) which is kind of annoying to implement.

My implementation can be found here, it might give you a few ideas!

This sounds sort of like the same thing. You need a base class where different type of profiles(?) can be stored, but only abstract methods for getting/setting these profiles. I kind of enjoy the pattern that the Identity base-classes provides, even though it's kind of annoying to implement, because it gives the implementer full freedom of what data-store (s)he wants to use.

From what i can tell from your question, each profile must have an Id which must be a System.Guid.

So why not start with an interface containing only this?

public interface IProfile
{
    Guid Id { get; }
}

Then why not implement a Store for the IProfile, such as in Identity

public abstract class ProfileStore<TProfile>
    where TProfile : class, IProfile
{
    public abstract Task<TProfile> FindByIdAsync(Guid profileId);
    public abstract Task<IEnumerable<TProfile>> FindManyAsync(Expression<Func<TProfile, bool>> query);
    public abstract Task SaveProfileAsync(TProfile profile);
}

You might (of course) want to add more methods of getting or saving your profiles.

All profile stores could then be added to some sort of ProfileStoreCollection where you can self-hydrate all stores by iterating over them, and invoking the InsertAsync-method.

This should be sufficient for what you are asking, please comment if i have missed some vital part!

Here is an example implementation (Using MongoDB and its latest driver):

A profile:

public class SomeProfile : IProfile
{
    [BsonId]
    public Guid Id { get; set; }

    public string Name { get; set; }

    public DateTime Expires { get; set; }
}

The store:

public class MongoDBProfileStore : ProfileStore<SomeProfile>
{
    private IMongoCollection<SomeProfile> _profileCollection;

    public MongoDBProfileStore(IMongoCollection<SomeProfile> profileCollection)
    {
        _profileCollection = profileCollection;
    }

    public override async Task<SomeProfile> FindByIdAsync(Guid profileId)
    {
        var filter = Builders<SomeProfile>.Filter
            .Eq(nameof(SomeProfile.Id), profileId);
        // the nameof-keyword is new in C#6 (returns "Id")

        var profiles = await _profileCollection.FindAsync(filter);
        await profiles.MoveNextAsync();

        if (profiles.Current != null)
        {
            return profiles.Current.FirstOrDefault();
        }
        return null;
    }

    public override async Task<IEnumerable<SomeProfile>> FindManyAsync(Expression<Func<SomeProfile, bool>> query)
    {
        var profiles = await _profileCollection.FindAsync(query);

        await profiles.MoveNextAsync();

        if (profiles.Current != null)
        {
            return profiles.Current.ToList();
        }
        return null;
    }

    public override async Task SaveProfileAsync(SomeProfile profile)
    {
        await _profileCollection.InsertOneAsync(profile);
    }
}


问:
Select design pattern - user stage
I'm struggling to point a finger into the right design pattern.

I have a web site which user can register and interact with the system.
I want to add the following abilities to a user:

Each user will be in a stage. Let's say that we have 5 stages.
when user is register, he will be in the 1-st stage.

User will be able to climb to the next stage.
To do so, he will need to complete X tasks.
(There will be 20 tasks in the system).

In each stage, the user will be able to buy benefits with the points that he gain in each task that he completed.

What's the appropriate design pattern to use here?

Thanks.

答:
You could be interested in State design pattern, which allows encapsulating varying behavior of an object based on its internal state.

If you're using MVC architectural pattern to build the web application you could think using it in the controller of the web application.

Title: Select design pattern - user stage


问:
What is the most obscure sorting algorithm you know?
I just read about cyclesort via a sortvis.org blog post.
This is probably the most obscure one I have heard of so far, since it uses maths that I am not familiar with (detecting cycles in permutations of integer sets).

What is the most obscure one you know?

答: For my data structures class I had to (explicitly) prove the correctness of Stooge sort. It has a running time of O(n^{log 3 / log 1.5}) = O(n^2.7095...).</p>


问:
Bounded contexts should contain just domain code?
In Domain-Driven Design there's the idea of bounded context which is basically a way to stablish a boundary within which a certain model is valid as far as I understood. I've found this idea very useful because prior to reading about it one of the main challenges I've faced to use object orientation correctly was the existence of ambiguities on the model (a Product class which depending on the context might mean something different, for example).

Now, although I think I understood a little the idea of bounded contexts, I'm yet unsure on how to implement this on practice.

My main doubt, which is what I'm asking in this question, is the following: when we are coding a bounded context, it should contain just domain code or be an entire application?

In some readings I've got the impression that a bounded context referred to an entire application. But this seems not to be in accordance to the understanding I've got and to the fact that DDD deals with just the domain model. In truth, IMHO most of the time we are interested in building one application, and it happens that there are different contexts within each the terms from the ubiquitous language, although the same, means different things. In that case we do not intend to build several applications, but just one.

In that case, when implementing DDD bounded contexts, they should contain just the domain model for that context, or be an entire application?

答:
If I'm understanding your question correctly, I don't think the bounded context has to be a separate application, though it may be.

If you were building, say, a hotel reservation system, you might have a "guest" context and a "hotel" context -- the Guest context might model names, addresses, rewards points, and the like; the Hotel context might model the properties, rooms, and so forth.

You could build those as two separate systems, perhaps as a set of Guest services and Hotel services that interact at carefully-defined points. Or you could build it as a single system, in which the two contexts inhabit the same codebase, but exist as separate, loosely-coupled packages or modules.

Either way, you're respecting the bounded contexts. Which path you choose would depend more on considerations such as product requirements, performance, scalability, team skillsets, and the like.

Where you would start to go wrong, of course, is if parts of the bounded contexts started to leak into each other -- if a class in the Hotel context were storing a Guest's room assignment, for example, that sounds like trouble.

You could, however, have a "Reservation" model that straddles the Guest and Hotel contexts. Again, though, this could all be part of the same codebase and application, or they could be separate applications that interact with each other. I would say that is an implementation detail, albeit an important one.


问:
What is the term for an anonymous JavaScript function that's called immediately?
I'm writing a JavaScript style-guide for my team, so that we can organise and contribute our documents easier.  But I've hit a small bump which is where my question applies...

What am I supposed to call an anonymous JavaScript function that's called immediately.  I know I could quite simply call it an "anonymous function", but I'd like to stress the fact that it's being called immediately.

Here is an example:

```<code>var MyVariable = (function(data){
  return "another value"
})("some value");

console.log(MyVariable);
// "another value"
</code>```

答:
They already have a term for that in the Javascript world. They are called Immediately Invoked Function Expressions (IIFE).

What it is

IIFE functions are not given a name. Instead, they are executed once as the interpreter comes across them:

```<code>var area = function() {
    var width = 3;
    var height = 2;
    return width * height;
}();
</code>```

The final parentheses after the closing curly brace of the code block tell the interpreter to call the function expression immediately.

If you write a function declaration you must add grouping operators, or parentheses surrounding the function, to tell the interpreter to treat the function as an expression that can be immediately invoked:

```<code>var area;
(function() {
    var width = 3;
    var height = 2;
    area = width * height;
}());
</code>```

When they are used

IIFEs are used for code that only needs to run once within a task, rather than being repeatedly called.

As an argument when a function is called (to calculate values, etc.)

To assign the value of a property to an object.

In event handlers and listeners.

To prevent conflicts between two scripts that might use the same variable names. They can be used as wrappers to drop code in another script where you're not sure if variable names may be the same.

Body:
They already have a term for that in the Javascript world. They are called Immediately Invoked Function Expressions (IIFE).

What it is

IIFE functions are not given a name. Instead, they are executed once as the interpreter comes across them:

var area = function() {
    var width = 3;
    var height = 2;
    return width * height;
}();

The final parentheses after the closing curly brace of the code block tell the interpreter to call the function expression immediately.

If you write a function declaration you must add grouping operators, or parentheses surrounding the function, to tell the interpreter to treat the function as an expression that can be immediately invoked:

var area;
(function() {
    var width = 3;
    var height = 2;
    area = width * height;
}());

When they are used

IIFEs are used for code that only needs to run once within a task, rather than being repeatedly called.

As an argument when a function is called (to calculate values, etc.)

To assign the value of a property to an object.

In event handlers and listeners.

To prevent conflicts between two scripts that might use the same variable names. They can be used as wrappers to drop code in another script where you're not sure if variable names may be the same.


问:
When did Undefined Behavior in C jump the causality barrier
Some hyper-modern C compilers will infer that if a program will invoke Undefined Behavior when given certain inputs, such inputs will never be received.  Consequently, any code which would be irrelevant unless such inputs are received may be eliminated.

As a simple example, given:

```<code>void foo(uint32_t);

uint32_t rotateleft(uint_t value, uint32_t amount)
{
  return (value << amount) | (value >> (32-amount));
}

uint32_t blah(uint32_t x, uint32_t y)
{
  if (y != 0) foo(y);
  return rotateleft(x,y);
}
</code>```

a compiler may infer that because evaluation of value >> (32-amount) will yield Undefined Behavior when amount is zero, function blah will never be called with y equal to zero; the call to foo can thus be made unconditional.

From what I can tell, this philosophy seems to have caught hold sometime around 2010.  The earliest evidence I've seen of its roots goes back to 2009, and it's been enshrined in the C11 standard which explicitly states that if Undefined Behavior occurs at any point in a program's execution, the behavior of the entire program retroactively becomes undefined.

Was the notion that compilers should attempt to use Undefined Behavior to justify reverse-causal optimizations (i.e. the Undefined Behavior in the rotateleft function should cause the compiler to assume that blah must have been called with a non-zero y, whether or not anything would ever cause y to hold a non-zero value) seriously advocated prior to 2009?  When was such a thing first seriously proposed as an optimization technique?

[Addendum]

Some compilers have, even in the 20th Century, included options to enable certain kinds of inferences about loops and the values computed therein.  For example, given

```<code>int i; int total=0;
for (i=n; i>=0; i--)
{
  doSomething();
  total += i*1000;
}
</code>```

a compiler, even without the optional inferences, might rewrite it as:

```<code>int i; int total=0; int x1000;
for (i=n, x1000=n*1000; i>0; i--, x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

since the behavior of that code would precisely match the original, even if the compiler specified that int values always wrap in mod-65536 two's-complement fashion.  The additional-inference option would let the compiler recognize that since i and x1000 should cross zero at the same time, the former variable can be eliminated:

```<code>int total=0; int x1000;
for (x1000=n*1000; x1000 > 0; x1000-=1000)
{
  doSomething();
  total += x1000;
}
</code>```

On a system where int values wrapped mod 65536, an attempt to run either of the first two loops with n equal to 33 would result in doSomething() being invoked 33 times.  The last loop, by contrast, wouldn't invoke doSomething() at all, even though the first invocation of doSomething() would have preceded any arithmetic overflow.  Such a behavior might be considered "non-causal", but the effects are reasonably well constrained and there many cases where the behavior would be demonstrably harmless (in cases where a function is required to yield some value when given any input, but the value may be arbitrary if the input is invalid, having the loop finish faster when given an invalid value of n would actually be beneficial).  Further, compiler documentation tended to be apologetic for the fact that it would change the behavior of any programs--even those that engaged in UB.

I'm interested in when compiler writers' attitudes changed away from the idea that platforms should when practical document some usable behavioral constraints even in cases not mandated by the Standard, to the idea that any constructs which would rely upon any behaviors not mandated by the Standard should be branded illegitimate even if on most existing compilers it would work as well or better than any strictly-compliant code meeting the same requirements (often allowing optimizations which would not be possible in strictly-compliant code).

答:
"Undefined behaviour might cause the compiler to rewrite code" has happened for a long time, in loop optimisations.

Take a loop (a and b are pointer to double, for example)

```<code>for (i = 0; i < n; ++i) a [i] = b [i];
</code>```

We increment an int, we copy an array element, we compare with a limit. An optimising compiler first removes the indexing:

```<code>double* tmp1 = a;
double* tmp2 = b;
for (i = 0; i < n; ++i) *tmp1++ = *tmp2++;
</code>```

We remove the case n <= 0:

```<code>i = 0;
if (n > 0) {
    double* tmp1 = a;
    double* tmp2 = b;
    for (; i < n; ++i) *tmp1++ = *tmp2++;
}
</code>```

Now we eliminate the variable i:

```<code>i = 0;
if (n > 0) {
    double* tmp1 = a;
    double* tmp2 = b;
    double* limit = tmp1 + n;
    for (; tmp1 != limit; tmp1++, tmp2++) *tmp1 = *tmp2;
    i = n;
}
</code>```

Now if n = 2^29 on a 32 bit system or 2^61 on a 64 bit system, on typical implementations we will have tmp1 == limit, and no code is executed. Now replace the assignment with something that takes a long time so that the original code will never run into the inevitable crash because it takes too long, and the compiler has changed the code.

Body:
"Undefined behaviour might cause the compiler to rewrite code" has happened for a long time, in loop optimisations.

Take a loop (a and b are pointer to double, for example)

for (i = 0; i < n; ++i) a [i] = b [i];

We increment an int, we copy an array element, we compare with a limit. An optimising compiler first removes the indexing:

double* tmp1 = a;
double* tmp2 = b;
for (i = 0; i < n; ++i) *tmp1++ = *tmp2++;

We remove the case n <= 0:

i = 0;
if (n > 0) {
    double* tmp1 = a;
    double* tmp2 = b;
    for (; i < n; ++i) *tmp1++ = *tmp2++;
}

Now we eliminate the variable i:

i = 0;
if (n > 0) {
    double* tmp1 = a;
    double* tmp2 = b;
    double* limit = tmp1 + n;
    for (; tmp1 != limit; tmp1++, tmp2++) *tmp1 = *tmp2;
    i = n;
}

Now if n = 2^29 on a 32 bit system or 2^61 on a 64 bit system, on typical implementations we will have tmp1 == limit, and no code is executed. Now replace the assignment with something that takes a long time so that the original code will never run into the inevitable crash because it takes too long, and the compiler has changed the code.


问:
White Boards -- Who Uses Them?
So as both a full-time programmer and hobbyist as well (developing my own things for personal use and maybe to sell one day), I feel that me purchasing a big white board to hang in my room at home or something would be very useful.

Does anyone here have one as well, to use for high level designs (UML, Architecture, etc.) and things like very early UI mockups, etc.?

If you guys do have them, which ones have you bought? I can't seem to pin one that would be good for home use and I'm not sure of the pricing/other things.

Thanks!

答:
I forget the specific name, but if you go to any hardware store you should be able to pick up big (4'x8') slabs of plastic white wall coverings, for bathrooms and the like.

They work well as whiteboards, are huge, and are way cheaper.

We had several in our dorm room in college for our bigger projects. I miss them now at work.

Alternatively I used to have a female co-worker that was fairly artsy.  She would get a big poster frame and put fancy but mono-chromatic patterned paper/cloth behind it.  Then used the frame as a whiteboard.

Title: White Boards -- Who Uses Them?


答:
I have seen large classes with documentation, and after reading the documentation I haven't got a clue what this class is supposed to be good for and why anyone would use it! And at the same time, I had a need for some functionality and I was absolutely sure there must be a class to handle it, and couldn't find it anywhere - because there was no documentation that led me from what I needed to the class doing it. </p>

<p>So the first thing that I would want in the documentation is just a few sentences what a class does, and why I would want to use it. The comments in the original question are doing quite well in that respect. After reading these comments, if I had a joystick that doesn't work well because I can't interpret the values it delivers, I would know what code to check. </p>

Body:
I have seen large classes with documentation, and after reading the documentation I haven't got a clue what this class is supposed to be good for and why anyone would use it! And at the same time, I had a need for some functionality and I was absolutely sure there must be a class to handle it, and couldn't find it anywhere - because there was no documentation that led me from what I needed to the class doing it.

So the first thing that I would want in the documentation is just a few sentences what a class does, and why I would want to use it. The comments in the original question are doing quite well in that respect. After reading these comments, if I had a joystick that doesn't work well because I can't interpret the values it delivers, I would know what code to check.


问:
Min weight feedback edge set with DFS?
Exercise from The Algorithm Design Manual

6-10. [4] Let G = (V,E) be an undirected graph. A set F ⊆ E of edges
is called a feedback-edge set if every cycle of G has at least one
edge in F.

(b) Suppose that G is a weighted undirected graph with
positive edge weights. Design an efficient algorithm to find a
minimum-weight feedback-edge set.

My proposed solution for (b) is to run DFS with getting max weight as the tie breaker. Then every back edge will always be the lowest weighted edge in its cycle. I'm wondering if this is a valid solution.

答:
Here is how I would tackle this problem.

For simplicity, let's just assume that G is connected (The algorithm to be described below can be easily extended for the case when G is not connected).

First, for any feedback-edge set F, it must be true that the graph G' = (V, E-F) doesn't have any cycle. This follows directly from the definition of feedback-edge sets.

Since we are looking for the set F that has minimum total weight, G' should be a tree and the edges in G' must have the maximum total weight possible (why ?)

→ G' must be a maximum spanning tree.

So now the original problem is reduced to finding a maximum spanning tree. You may already know that the Kruskal's algorithm can be used for finding a minimum spanning tree. With a little modification, you can use Kruskal's algorithm to find a maximum spanning tree. https://stackoverflow.com/questions/4992664/how-to-find-maximum-spanning-tree

So in conclusion, the algorithm I just described has running time of O(E log V) time (which is just the running time of Kruskal's algorithm)

Title: Min weight feedback edge set with DFS?


问:
Is it bad to store data in JSON form or should I use mySQL?
I've been building an application and the whole thing is built around a simple data storage system.

Create an array.

Convert it into JSON.

Add <?php die() at the beginning to prevent access.

Save to PHP file and save to disk.

Then.

Open file.

Remove <?php die();.

Decode it from JSON.

Edit/Read array.

Save it back to file if edited.

Is this a safe way to store data? When I made this I didn't know MySQL, and I still don't know it that well. However, I want to make the choice to whether to edit my platform while it is small and change it to MySQL or to keep using the current system.

I've never encountered issues with a file being edited at the same time, and it doesn't seem to make the website slower at the moment.

Is it worth changing my medium sized application now, and not face having to spend weeks changing it now it is growing? Or is the current system secure enough to keep using.

This is what the system currently works from;

Setting data:

```<code>function setDat($dat_file, $sec, $subsec, $val) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    $dat_file_dat[$sec][$subsec] = [$val];
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php', "<?php die(); ".json_encode($dat_file_dat));
}
</code>```

Getting data:

```<code>function getDat($dat_file, $sec, $subsec) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    return $dat_file_dat[$sec][$subsec][0];
}
</code>```

And so on.

If I explain this:

$dat_file is the file that the data will be stored in, a file within /data/

$sec is the top level of the array you want to edit $array[$sec];

$subsec is the second level array $array[$sec][$subsec];

I do this because each application can use the $sec as the category for the data, and the $subsec and the search within their category. They can also have their own file. So the file main-settings has a category called theme-settings and then some information like active-theme which is set to default.

So this being said, it it worth keeping the current system and will it cope in the future? What are its weaknesses, and any problems with it.

OR

Should I start to change everything to MySQL, even though I will have to reprogram the whole data side of my program? What are the upsides to this and downsides?

答:
If you want to go with the file approach and have mostly static and configuration data use SQLite (PHP entry): it is a RDBMS just like MySQL, but it is a local single file in a directory of your choice (it can even be in your application's folder), installation free, lightweight and can accomplish your data requirements with consistency and a lot of tested hard work behind it – there, all done for you without you having to worry about a new kind of data management. Data migration with SQLite involves basically moving/copying the .sqlite file.

For anything a little larger just go with MySQL or PostgreSQL.


问:
Liskov substitution and abstract classes / strategy pattern
I'm trying to follow LSP in practical programming. And I wonder if different constructors of subclasses violate it. It would be great to hear an explanation instead of just yes/no. Thanks much!

P.S. If the answer is no, how do I make different strategies with different input without violating LSP?

```<code>class IStrategy
{
    public:
        virtual void use() = 0;
};

class FooStrategy : public IStrategy
{
    public:
        FooStrategy(A a, B b) { c = /* some operations with a, b */ }
        virtual void use() { std::cout << c; }
    private:
        C c;
};

class BarStrategy : public IStrategy
{
    public:
        BarStrategy(D d, E e) { f = /* some operations with d, e */ }
        virtual void use() { std::cout << f; }
    private:
        F f;
};
</code>```

答:
TL;DR: Different subtype constructors are not only ok, they are expected.

Liskov directly addresses the usage of different constructors in her paper Behavioral Subtyping Using Invariants and Constraints which is the formalization of the principle.

"..omitting creators [from the type specification] makes it easy for a type to have multiple implementations, allows new creators to be added later, and reflects common usage"

This then shows that alternative constructors in the subtype are not only okay, but expected.  It is also further addressed explicitly in the summary of the paper.


问:
Should a method be forgiving with the arguments that are passed in?
Suppose we have a method foo(String bar) that only operates on strings that meet certain criteria; for example, it must be lowercase, must not be empty or have only whitespace, and must match the pattern [a-z0-9-_./@]+. The documentation for the method states these criteria.

Should the method reject any and all deviations from this criteria, or should the method be more forgiving about some criteria? For example, if the initial method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
    }
    this.bar = bar;
}
</code>```

And the second forgiving method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        bar = bar.toLowerCase().trim().replaceAll(" ", "_");
        if (!bar.matches(BAR_PATTERN_STRING) {
            throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
        }
    }
    this.bar = bar;
}
</code>```

Should the documentation be changed to state that it will be transformed and set to the transformed value if possible, or should the method be kept as simple as possible and reject any and all deviations? In this case, bar could be set by the user of an application.

The primary use-case for this would be users accessing objects from a repository by a specific string identifier. Each object in the repository should have a unique string to identify it. These repositories could store the objects in various ways (sql server, json, xml, binary, etc) and so I tried to identify the lowest common denominator that would match most naming conventions.

答:
Your method should do what it says it does.

This prevents bugs, both from use and from maintainers changing behavior later. It saves time because maintainers don't need to spend as much time figuring out what is going on.

That said, if the defined logic isn't user friendly, it should perhaps be improved.


问:
How do you take advantage of your whiteboard in your development team?
Today we got our own website design. The theme is the "whiteboard".

I'm a big fan of them. I would like you to share with me how you use it. I'm sure I don't exploit its potential enough.

I will really enjoy answers that will come with pictures of your own whiteboard as an illustration ;)

I use it as an information radiator to support a light version of scrum.

How do you use this essential development tool?

Please note that I'm also interested in people using a virtual whiteboard or even big touchscreen whiteboard emulator.

答:
Whileboards are like wikis; they encourage low-impact collaboration.

Because they don't have history, it's easy to destroy state. Electronic whiteboards help record state, but make it slightly harder and more intimidating to contribute because the 'in print' nature of the display make it feel more permanent.

We use whiteboards to:

brainstorm design ideas

move ideas from stickies to drawn designs

help explain complex concepts

draw out design alternatives (UI or architectural)

draw large sketches to help explore a design space

as mixed media surfaces (like the one shown above) for sorting and marking up stickies or information generated in some other way (e.g. printed-out screenshots)

This can be using the in-office whiteboards or the ones in the conference rooms.

We also have whiteboards outside our offices that are more like the ones in college dorms--places to leave notes and messages to each other.