问:
Do enums create brittle interfaces?
Consider the example below.  Any change to the ColorChoice enum affects all IWindowColor subclasses.

Do enums tend to cause brittle interfaces?  Is there something better than an enum to allow for more polymorphic flexibility?

```<code>enum class ColorChoice
{
    Blue = 0,
    Red = 1
};

class IWindowColor
{
public:
    ColorChoice getColor() const=0;
    void setColor( const ColorChoice value )=0;
};
</code>```

Edit:  sorry for using color as my example, that's not what the question is about.  Here is a different example that avoids the red herring and provides more info about what I mean by flexibility.

```<code>enum class CharacterType
{
    orc = 0,
    elf = 1
};

class ISomethingThatNeedsToKnowWhatTypeOfCharacter
{
public:
    CharacterType getCharacterType() const;
    void setCharacterType( const CharacterType value );
};
</code>```

Further, imagine that handles to the appropriate ISomethingThatNeedsToKnowWhatTypeOfCharacter subclass are handed out by a factory design pattern.  Now I have an API that cannot be extended in the future for a different application where the allowable character types are { human, dwarf }.

Edit: Just to be more concrete about what I'm working on.  I am designing a strong binding of this (MusicXML) specification and I am using enum classes to represent those types in the specification which are declared with xs:enumeration.  I am trying to think about what happens when the next version (4.0) comes out.  Could my class library work in a 3.0 mode and in a 4.0 mode?  If the next version is 100% backward compatible, then maybe.  But if enumeration values were removed from the specification then I'm dead in the water.

答:
When used properly, enums are far more readable and robust than the "magic numbers" they replace. I don't normally see them making code more brittle. For instance:

setColor() doesn't have to waste time checking if value is a valid color value or not. The compiler has already done that.

You can write setColor(Color::Red) instead of setColor(0). I believe the enum class feature in modern C++ even lets you force people to always write the former instead of the latter.

Usually not important, but most enums can be implemented with any size integral type, so the compiler can choose whatever size is most convenient without forcing you to think about such things.

However, using an enum for color is questionable because in many (most?) situations there's no reason to limit the user to such a small set of colors; you might as well let them pass in any arbitrary RGB values. On the projects I work with, a small list of colors like this would only ever come up as part of a set of "themes" or "styles" that's supposed to act as a thin abstraction over concrete colors.

I'm not sure what your "polymorphic flexibility" question is getting at. Enums don't have any executable code, so there's nothing to make polymorphic. Perhaps you're looking for the command pattern?

Edit: Post-edit, I'm still not clear on what kind of extendability you're looking for, but I still think the command pattern is the closest thing you'll get to a "polymorphic enum".

Title: Do enums create brittle interfaces?


答:
Any change to the ColorChoice enum affects all IWindowColor subclasses.

No it doesn't.  There are two cases:  implementers will either

store, return and forward enum values, never operating on them, in which case they are unaffected by changes in the enum, or

operate on individual enum values, in which case any change in the enum must of course, naturally, inescapably, necessarily, be accounted for with a corresponding change in the logic of the implementer.

If you put "Sphere", "Rectangle", and "Pyramid" in a "Shape" enum, and pass such an enum to some drawSolid() function which you have written to draw the corresponding solid, and then one morning you decide to add an "Ikositetrahedron" value to the enum, you cannot expect the drawSolid() function to remain unaffected;  If you did expect it to somehow draw icositetrahedrons without you first having to write the actual code to draw icositetrahedrons, that's your fault, not the enum's fault.  So:

Do enums tend to cause brittle interfaces?

No, they don't.  What causes brittle interfaces is programmers thinking of themselves as ninjas, trying to compile their code without having sufficient warnings enabled.  Then, the compiler does not warn them that their drawSolid() function contains a switch statement which is missing a case clause for the newly added "Ikositetrahedron" enum value.

The way it is supposed to work is analogous to adding a new pure virtual method to a base class: you then have to implement this method on every single inheritor, or else the project does not, and should not, build.

Now, truth be told, enums are not an object-oriented construct.  They are more of a pragmatic compromise between the object-oriented paradigm and the structured programming paradigm.

The pure object-oriented way of doing things is not having enums at all, and instead having objects all the way.

So, the purely object-oriented way to implement the example with the solids is of course to use polymorphism: instead of having a single monstrous centralized method which knows how to draw everything and having to be told which solid to draw, you declare a "Solid" class with an abstract (pure virtual) draw() method, and then you add "Sphere", "Rectangle" and "Pyramid" subclasses, each having its own implementation of draw() which knows how to draw itself.

This way, when you introduce the "Ikositetrahedron" subclass, you will just have to provide a draw() function for it, and the compiler will remind you to do that, by not letting you instantiate "Icositetrahedron" otherwise.

ContentLicense: CC BY-SA 3.0

Title: Do enums create brittle interfaces?

Body:
Consider the example below.  Any change to the ColorChoice enum affects all IWindowColor subclasses.

Do enums tend to cause brittle interfaces?  Is there something better than an enum to allow for more polymorphic flexibility?

```<code>enum class ColorChoice
{
    Blue = 0,
    Red = 1
};

class IWindowColor
{
public:
    ColorChoice getColor() const=0;
    void setColor( const ColorChoice value )=0;
};
</code>```

Edit:  sorry for using color as my example, that's not what the question is about.  Here is a different example that avoids the red herring and provides more info about what I mean by flexibility.

```<code>enum class CharacterType
{
    orc = 0,
    elf = 1
};

class ISomethingThatNeedsToKnowWhatTypeOfCharacter
{
public:
    CharacterType getCharacterType() const;
    void setCharacterType( const CharacterType value );
};
</code>```

Further, imagine that handles to the appropriate ISomethingThatNeedsToKnowWhatTypeOfCharacter subclass are handed out by a factory design pattern.  Now I have an API that cannot be extended in the future for a different application where the allowable character types are { human, dwarf }.

Edit: Just to be more concrete about what I'm working on.  I am designing a strong binding of this (MusicXML) specification and I am using enum classes to represent those types in the specification which are declared with xs:enumeration.  I am trying to think about what happens when the next version (4.0) comes out.  Could my class library work in a 3.0 mode and in a 4.0 mode?  If the next version is 100% backward compatible, then maybe.  But if enumeration values were removed from the specification then I'm dead in the water.


问:
Sharing state with dependencies - Object-Oriented Design
Suppose that I define two interfaces below:

```<code>public interface IReader
{
    void Read(string bookName);
}

public interface IWriter
{
    void Write(string bookName);
}
</code>```

Now I want to implement IReader interface like this:

```<code> public class Reader : IReader
{
    private IEnumerable<string> _books;

    public Reader(IEnumerable<string> books)
    {
        _books = books; // List of books is given through constructor
    }

    public void Read(string bookName)
    {
        if (_books.Contains(bookName))
        {
            // Reading here
        }
        else
        {
            throw new InvalidOperationException("Given book name was not found in the library.");
        }
    }
}
</code>```

And now I want to define a higher-level class which implements both the two interfaces:

```<code>public class Person : IReader, IWriter
{
    // This is the data I want to share with IReader argument of constructor
    private IList<string> _books = new List<string>();
    private IReader _reader;

    public Person(IReader reader)
    {
        _reader = reader; // How do I share books with this object?
    }

    public void Read(string bookName)
    {
        _reader.Read(bookName);
    }

    public void Write(string bookName)
    {
        _books.Add(bookName);
    }
}
</code>```

As you noticed I used composition to implement the IReader interface. I need to inject an instance of Reader to the Person class but I also need to share my Person's books data with the Reader instance. This is the problem I want to solve.

So far we didn't provide a way to share the list of books with the IReader interface. A few options come to my mind:

First option: Create an IReaderFactory interface and its implementation which creates an instance like this:

```<code>public interface IReaderFactory
{
    IReader Create(IEnumerable<string> books);
}

public class ReaderFactory : IReaderFactory
{
    public IReader Create(IEnumerable<string> books)
    {
        return new Reader(books);
    }
}
</code>```

This is all good, now I can inject IReaderFactory to my Person constructor instead of IReader. The downside is that it requires 2 extra definitions IReaderFactory, and ReaderFactory.

Second option: Add another method to IReader interface like this:

```<code>void Initialize(IEnumreable<string> books);
</code>```

This works too, in the Person's constructor I can call this method and pass my books to it. But it doesn't seem elegant to me, because now I have to remember calling this method, and this method can be called many times, which is something we don't want.

I don't want to use a DI container and resolve an instance of IReader inside Person's constructor because it hides the dependencies of the Person class.

Now, what is the best way to go in this kind of situation without violating Dependency Inversion Principle ?

答:
A third option might involve creating a class to manage the state of your books, then sharing an instance of the class with your Person and IReader implementations. This is conceptually similar to having a book repository or cache. Option 1 or my suggestion are probably the cleaner solutions.

Can you provide more information about the overall problem you are trying to model? I have a feeling that it can be modeled slightly differently and your issue will just go away.


问:
Finding the first subarray that sums to a given total
Here is the question:

Given and unordered array of positive and negative integers. How can you find the first subarray to sum to a given value?

For example. Given the array...

```<code>[1, -3, 4, 8, 2, -14, 3, -1, 10, 6]
</code>```

Find the first subarray to sum to 9.

In this example the sub array would be...

```<code>[-3, 4, 8]
</code>```

I found a solution that is O(n^2) by iterating the array for start points and then iterating every end point until you find the value.

But is there a way to do this better than O(n^2)?

答:
What about this?

We run through the array, computing the sums of all the prefixes along the way. (O(n) since we can keep a running tally of the sum)

We save the sums we encounter in some datastructure where we can search by the value of the sum and also get prefix that the sum belongs to (see below for implementation of this)

If the sum of the prefix up to index n is off target by an amount that is the sum of a prefix we previously encountered, say, up to index m, then we found our subarray, the array from m to n. Since sum(prefix(n)) - sum(prefix(m)) = targetSum and subArray(m,n) = prefix(n) - prefix(m) (hopefully this psuedo-notation is somewhat clear)

Now the running time of our algorithm is n * (the time it takes to insert the sum of our prefix to the datastructure + the time it takes to search if we have a certain sum in our datastructure).

An obvious choice for a datastructure would be a hashtable with sums as keys and the prefix they are the sum of as values. Here search and insert take O(1) on average, so we would be O(n) on average, which seems rather decent. Code could be:

public int[] findSubArray(int[] arr, int targetSum){
    Map<Integer, Integer> sumsToIndex = new HashMap<Integer, Integer>();
    int sum = 0;

    for(int index = 0; index <= arr.length; index++){
        if(sumsToIndex.get(sum) == null){
            sumsToIndex.put(sum, index);
        }

        int offTarget = sum - targetSum;
        Integer offTargetPrefix = sumsToIndex.get(offTarget);
        if(offTargetPrefix != null){
            return Arrays.copyOfRange(arr, offTargetPrefix, index);
        }

        if(index < arr.length){
            sum += arr[index];
        }
    }
    return null;
}
```

However worst case, search in a hashtable is O(n) if we get a boatload of collisions, I don't know how this pans out here. Since our keys are integers, I think we might be okay. But maybe theoretically we are still O(n) worst case. Making our algorithm O(n^2) still.

What we could do is use some other datastructure, like red-black trees (with the sums as sorting key), where search and insertion are O(log n) in the worst case, making our algorithm O(n log(n)).

Body:
What about this?

We run through the array, computing the sums of all the prefixes along the way. (O(n) since we can keep a running tally of the sum)

We save the sums we encounter in some datastructure where we can search by the value of the sum and also get prefix that the sum belongs to (see below for implementation of this)

If the sum of the prefix up to index n is off target by an amount that is the sum of a prefix we previously encountered, say, up to index m, then we found our subarray, the array from m to n. Since sum(prefix(n)) - sum(prefix(m)) = targetSum and subArray(m,n) = prefix(n) - prefix(m) (hopefully this psuedo-notation is somewhat clear)

Now the running time of our algorithm is n * (the time it takes to insert the sum of our prefix to the datastructure + the time it takes to search if we have a certain sum in our datastructure).

An obvious choice for a datastructure would be a hashtable with sums as keys and the prefix they are the sum of as values. Here search and insert take O(1) on average, so we would be O(n) on average, which seems rather decent. Code could be:

public int[] findSubArray(int[] arr, int targetSum){
    Map<Integer, Integer> sumsToIndex = new HashMap<Integer, Integer>();
    int sum = 0;

    for(int index = 0; index <= arr.length; index++){
        if(sumsToIndex.get(sum) == null){
            sumsToIndex.put(sum, index);
        }

        int offTarget = sum - targetSum;
        Integer offTargetPrefix = sumsToIndex.get(offTarget);
        if(offTargetPrefix != null){
            return Arrays.copyOfRange(arr, offTargetPrefix, index);
        }

        if(index < arr.length){
            sum += arr[index];
        }
    }
    return null;
}

However worst case, search in a hashtable is O(n) if we get a boatload of collisions, I don't know how this pans out here. Since our keys are integers, I think we might be okay. But maybe theoretically we are still O(n) worst case. Making our algorithm O(n^2) still.

What we could do is use some other datastructure, like red-black trees (with the sums as sorting key), where search and insertion are O(log n) in the worst case, making our algorithm O(n log(n)).


答:
If you are careful in how you use them, I'd not consider enums harmful. But there are a few things to consider if you want to use them in some library code, as opposed to a single application.

Never remove or reorder values. If you at some point have an enum value in your list, that value should be associated with that name for all eternity. If you want to, you can at some point rename values to deprecated_orc or whatever, but by not removing them you can more easily maintain compatibility with old code compiled against the old set of enums. If some new code can't deal with old enum constants, either generate a suitable error there or make sure no such value reaches that piece of code.

Don't do arithmetic on them. In particular, don't do order comparisons. Why? Because then you might encounter a situation where you can't keep existing values and preserve a sane ordering at the same time. Take for example an enum for compass directions: N=0, NE=1, E=2, SE=3, … Now if after some update you include NNE and so on between the existing directions, you can either add them to the end of the list and thus break the ordering, or you interleave them with existing keys and thus break established mappings used in legacy code. Or you deprecate all the old keys, and have a completely new set of keys, along with some compatibility code which translates between old and new keys for the sake of legacy code.

Choose a sufficient size. By default the compiler will use the smallest integer that can contain all enum values. Which means that if, at some update, your set of possible enums expands from 254 to 259, you suddenly need 2 bytes for every enum value instead of one. This could break structure and class layouts all over the place, so try to avoid this by using a sufficient size in the first design. C++11 gives you a lot of control here, but otherwise specifying an entry LAST_SPECIES_VALUE=65535 should help as well.

Have a central registry. Since you want to fix the mapping between names and values, it is bad if you let third party users of your code add new constants. No project using your code should be allowed to alter that header to add new mappings. Instead they should bug you to add them. This means that for the human and dwarf example you mentioned, enums are indeed a poor fit. There it would be better to have some kind of registry at run-time, where users of your code can insert a string and get back a unique number, nicely wrapped in some opaque type. The “number” might even be a pointer to the string in question, it doesn't matter.

Despite the fact that my last point above makes enums a poor fit for your hypothetical situation, your actual situation where some spec might change and you'd have to update some code seems to fit in quite well with a central registry for your library. So enums should be appropriate there if you take my other suggestions to heart.

Title: Do enums create brittle interfaces?


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答: I have the Nook Color and unfortunately it doesn't render source code very well when the books are in actual ebook formats.  But if they are in PDF format, then it is ok in landscape mode at the right zoom level.</p>

ContentLicense: CC BY-SA 2.5

Title: eBook editions of programming books

OwnerDisplayName: Dan


答:
Enums are a great improvement over magic identification numbers for closed sets of values that do not have a lot of functionality associated with them. Usually you don't care about what number is actually associated with the enum; in this case it is easy to extend by adding new entries at the end, no brittleness should result.

The problem is when you have significant functionality associated with the enum. That is, you have this kind of code lying around:

```<code>switch (my_enum) {
case orc: growl(); break;
case elf: sing(); break;
...
}
</code>```

One or two of these is ok, but as soon as you have this kind of meaningful enum, these switch statements tend to multiply like tribbles. Now every time you extend the enum, you need to hunt down all the associated switches to make sure you've covered everything. This is brittle. Sources such as Clean Code will suggest that you should have one switch per enum, at most.

What you should do instead in this case is to use OO principles and create an interface for this type. You may still keep the enum for communicating this type, but as soon as you need to do anything with it, you create an object associated with the enum, possibly using a Factory. This is much easier to maintain, as you only need to look for one place to update: your Factory, and by adding a new class.

Title: Do enums create brittle interfaces?

Body:
Enums are a great improvement over magic identification numbers for closed sets of values that do not have a lot of functionality associated with them. Usually you don't care about what number is actually associated with the enum; in this case it is easy to extend by adding new entries at the end, no brittleness should result.

The problem is when you have significant functionality associated with the enum. That is, you have this kind of code lying around:

switch (my_enum) {
case orc: growl(); break;
case elf: sing(); break;
...
}

One or two of these is ok, but as soon as you have this kind of meaningful enum, these switch statements tend to multiply like tribbles. Now every time you extend the enum, you need to hunt down all the associated switches to make sure you've covered everything. This is brittle. Sources such as Clean Code will suggest that you should have one switch per enum, at most.

What you should do instead in this case is to use OO principles and create an interface for this type. You may still keep the enum for communicating this type, but as soon as you need to do anything with it, you create an object associated with the enum, possibly using a Factory. This is much easier to maintain, as you only need to look for one place to update: your Factory, and by adding a new class.


问:
Security scheme that prevents duplicate message attacks
I am using custom security scheme to verify communication between client and server.

Both client and server have same secret hash phrase.

Client builds a message, combines it with hash phrase and calculates
SHA512 hash, and sends both message and hash to server

Server receives a message, combines it with hash phrase and
calculates SHA512 hash, and then verifies that hash is the same as
the one sent by client

This scheme works fine, but allows man in the middle to sniff the message and send it again, again and again to server.

Now, I know how to solve this, for example, by assigning unique id to each message and rejecting duplicates - but these unique ids must be stored somewhere (database, session, ...)

Is there some more stateless approach that can solve this problem?

答:
Nonce is used for just that

it's a number, possibly passed in the message header and it can be only used once and the subsequent requests with the same number are rejected by the serve.

For details on how the value is determined please have a look at the article.


问:
Why did programming languages start using = for assignment?
In most early algorithms books, <- referred to assignment and = referred to comparison. But nowadays the only languages that don't use = for assignment are Pascal (:=) and toy languages like COOL. What caused modern programming languages to change = into meaning assignment instead of its mathematical meaning of equality?

答:
According to Wikipedia, the use of equals for assignment dates back to Heinz Rutishauser's language Superplan, designed from 1949 to 1951, and was particularly popularized by Fortran:

A notorious example for a bad idea was the choice of the equal sign to denote assignment. It goes back to Fortran in 1957, and has blindly been copied by armies of language designers. Why is it a bad idea? Because it overthrows a century old tradition to let “=” denote a comparison for equality, a predicate which is either true or false. But Fortran made it to mean assignment, the enforcing of equality. In this case, the operands are on unequal footing: The left operand (a variable) is to be made equal to the right operand (an expression). x = y does not mean the same thing as y = x.

—Niklaus Wirth, Good Ideas, Through the Looking Glass

Konrad Zuse also used the equals sign for Plankalkul, which inspired Rutishauser's Superplan, although a compiler was never devised for it.  Why did he choose the equals sign?  I guess you'd have to ask him.

ContentLicense: CC BY-SA 4.0


答:
But when I did math at school
  "let x = 123 "

was common phrasing. Early versions of Basic insisted on the "let" keyword before the equal. So its basically boils done to "let" is understood.

A key driver not usually considered but very important at the time it what did you actually type on.

There were two feasible input devices,

The "teletype" whereby you could use a standard teletype machine to punch little holes in a paper ribbon which could then be read by the computer. This was not so bad as it supported the standard aplphabet in upper and lower case plus most of the characters on the top row of your keyboard.

Punched cards -- there were lots of punch card machines hanging around as the use of sorters, tabulators and printers was common in large corporations. These supported a ery limited character set Upper case only alphabet and a limited number of "special" characters.

Teletypes tended to be used in academic and military shops, card punches in more commercial shops. Hence academic languages like Pascal supported lower case identifiers and "sensible" notations like ":=" for assignment. Languages aimed at a more commercial audience assumed that punched cards would be the main form of input hence the Upper case only languages like FORTRAN and COBOL with there limited support for ":;><" characters which were unavailable on a standard keypunch.

Incidentally there was no ambiguity about "=" being used for assignment in early FORTRAN as comparison was done using the ".LT.", ".LE.", ".EQ.", ".GE." and ".GT." syntax.

Title: Why did programming languages start using = for assignment?

Body: In most early algorithms books, <- referred to assignment and = referred to comparison. But nowadays the only languages that don't use = for assignment are Pascal (:=) and toy languages like COOL. What caused modern programming languages to change = into meaning assignment instead of its mathematical meaning of equality?


答:
Enums do not create brittle interfaces. Misuse of enums does.

What are enums for?

Enums are designed to be used as sets of meaningfully named constants. They are to be used when:

You know that no values will be removed.

(And) You know it is highly unlikely that a new value will be needed.

(Or) You accept that a new value will be needed, but rarely enough to warrant fixing all the code that breaks because of it.

Good uses of enums:

Days of the week: (as per .Net's System.DayOfWeek) Unless you are
dealing with some incredibly obscure calender, there will only ever
be 7 days of the week.

Non-extensible colours: (as per .Net's System.ConsoleColor) Some
may disagree with this, but .Net chose to do this for a reason. In
.Net's console system, there are only 16 colours available for use by
the console. These 16 colours correspond to the legacy colour palette
known as CGA or 'Color Graphics Adapter'. No new values will
ever be added, which means that this is in fact a reasonable
application of an enum.

Enumerations representing fixed states: (as per Java's
Thread.State) The designers of Java decided that in the Java
threading model there will only ever be a fixed set of states that a
Thread can be in, and so to simplify matters, these different
states are represented as enumerations. This means that many
state-based checks are simple ifs and switches which in practise
operate on integer values, without the programmer having to worry
about what the values actually are.

Bitflags representing non-mutually exclusive options: (as per .Net's System.Text.RegularExpressions.RegexOptions) Bitflags are a
very common use of enums. So common in fact, that in .Net all enums
have a HasFlag(Enum flag) method built in. They also support the
bitwise operators and there's a FlagsAttribute to mark an enum as
being intended to be used as a set of bitflags. By using an enum as a
set of flags, you can represent a group of boolean values in a single
value, as well as having the flags clearly named for convenience.
This would be extremely beneficial for representing the flags of a
status register in an emulator or for representing the permissions of
a file (read, write, execute), or just about any situation where a
set of related options are not mutually exclusive.

Bad uses of enums:

Character classes/types in a game: Unless the game is a one-shot demo
that you are unlikely to use again, enums should not be used for
character classes because chances are you will want to be adding a
lot more classes. It is better to have a single class representing
character and have an in-game character 'type' represented otherwise.
One way to handle this is the TypeObject pattern, other
solutions include registering character types with a dictionary/type
registry, or a mixture of the two.

Extensible colours: If you're using an enum for colours that may
later be added to it is not a good idea to represent this in enum
form, else you will be left forever adding colours. This is similar
to the issue above, thus a similar solution should be used (i.e. a
variation of TypeObject).

Extensible state: If you've got a state machine that may end up
introducing many more states, it is not a good idea to represent
these states via enumerations. The preferred method is to define an
interface for the machine's state, provide an implementation or class
that wraps the interface and delegates its method calls (akin to the
Strategy pattern), and then alters its state by changing which
provided implementation is currently active.

Bitflags representing mutually exclusive options: If you're using enums to represent flags and two of those flags should never occur
together then you have shot yourself in the foot. Anything that is
programmed to react to one of the flags will suddenly react to
whichever flag it's programmed to respond to first - or worse, it
might respond to both. This sort of situation is just asking for
trouble. The best approach is to treat the absence of a flag as the alternative condition if possible (i.e. the absence of the True flag implies False). This behaviour can be further supported through the use of specialised functions (i.e. IsTrue(flags) and IsFalse(flags)).

Title: Do enums create brittle interfaces?


答:
DIP states that Higher level module should depend on Lower level module over abstraction and All variable implementations require Factory Method.Ref: DIP

So, creating a Factory Class definitely a good option to resolve your problem.

In addition, you could inject both IReader and Iwriter to your Person class.

```<code>public class Person : IReader, IWriter
{
    private IReader _reader;
    private IWriter _writer;

    public Person(IReader reader, IWriter writer)
    {
       _reader = reader;
       _writer = writer;
    }

    public void Read(string bookName)
    {
       _reader.Read(bookName);
    }

    public void Write(string bookName)
    {
       _writer.Write(bookName);
    }
}
</code>```

For creating a Person object you can use Factory pattern.

```<code>public interface IPersonFactory
{
  Person Create(IEnumerable<string> books);
}

public class PersonFactory : IPersonFactory
{
  public Person Create(IEnumerable<string> books)
  {
    IWriter = new Writer(books); // if needed use factory class here
    IReader = new Reader(books); // if needed use factory class here
    return new Person(IReader, IWriter);
  }
}
</code>```

Title: Sharing state with dependencies - Object-Oriented Design

Body:
Suppose that I define two interfaces below:

```<code>public interface IReader
{
    void Read(string bookName);
}

public interface IWriter
{
    void Write(string bookName);
}
</code>```

Now I want to implement IReader interface like this:

```<code> public class Reader : IReader
{
    private IEnumerable<string> _books;

    public Reader(IEnumerable<string> books)
    {
        _books = books; // List of books is given through constructor
    }

    public void Read(string bookName)
    {
        if (_books.Contains(bookName))
        {
            // Reading here
        }
        else
        {
            throw new InvalidOperationException("Given book name was not found in the library.");
        }
    }
}
</code>```

And now I want to define a higher-level class which implements both the two interfaces:

```<code>public class Person : IReader, IWriter
{
    // This is the data I want to share with IReader argument of constructor
    private IList<string> _books = new List<string>();
    private IReader _reader;

    public Person(IReader reader)
    {
        _reader = reader; // How do I share books with this object?
    }

    public void Read(string bookName)
    {
        _reader.Read(bookName);
    }

    public void Write(string bookName)
    {
        _books.Add(bookName);
    }
}
</code>```

As you noticed I used composition to implement the IReader interface. I need to inject an instance of Reader to the Person class but I also need to share my Person's books data with the Reader instance. This is the problem I want to solve.

So far we didn't provide a way to share the list of books with the IReader interface. A few options come to my mind:

First option: Create an IReaderFactory interface and its implementation which creates an instance like this:

```<code>public interface IReaderFactory
{
    IReader Create(IEnumerable<string> books);
}

public class ReaderFactory : IReaderFactory
{
    public IReader Create(IEnumerable<string> books)
    {
        return new Reader(books);
    }
}
</code>```

This is all good, now I can inject IReaderFactory to my Person constructor instead of IReader. The downside is that it requires 2 extra definitions IReaderFactory, and ReaderFactory.

Second option: Add another method to IReader interface like this:

```<code>void Initialize(IEnumreable<string> books);
</code>```

This works too, in the Person's constructor I can call this method and pass my books to it. But it doesn't seem elegant to me, because now I have to remember calling this method, and this method can be called many times, which is something we don't want.

I don't want to use a DI container and resolve an instance of IReader inside Person's constructor because it hides the dependencies of the Person class.

Now, what is the best way to go in this kind of situation without violating Dependency Inversion Principle ?

Body:
DIP states that Higher level module should depend on Lower level module over abstraction and All variable implementations require Factory Method.Ref: DIP

So, creating a Factory Class definitely a good option to resolve your problem.

In addition, you could inject both IReader and Iwriter to your Person class.

public class Person : IReader, IWriter
{
    private IReader _reader;
    private IWriter _writer;

    public Person(IReader reader, IWriter writer)
    {
       _reader = reader;
       _writer = writer;
    }

    public void Read(string bookName)
    {
       _reader.Read(bookName);
    }

    public void Write(string bookName)
    {
       _writer.Write(bookName);
    }
}

For creating a Person object you can use Factory pattern.

public interface IPersonFactory
{
  Person Create(IEnumerable<string> books);
}

public class PersonFactory : IPersonFactory
{
  public Person Create(IEnumerable<string> books)
  {
    IWriter = new Writer(books); // if needed use factory class here
    IReader = new Reader(books); // if needed use factory class here
    return new Person(IReader, IWriter);
  }
}


问:
What is the difference between data retention and data archival?
The article at http://www.complianceguru.com/2010/11/archiving-vs-retention-of-email-and-other-electronic-data/ seems to suggest there is a difference. It isn’t very clear though what if the difference is apart for the length of time it may be stored.

The description below also suggests that other than archived data e.g. retained data is mutable or changeable.

Now, retention vs. archiving: Think of an archive as a non-alterable backup.  Some archive solutions also add a search feature, but the key is that the data cannot be deleted or modified in any way.  So why consider archiving instead of simple retention?

Is there a difference and if so what are the differences?

答:
Archiving -- take a copy and store it somewhere else.

Retention -- how long you keep the data in a particular store.

So you might archive a copy of your payroll database to tape once a month and send it to an offsite warehouse. So if the IRS demand to know how much you paid Joe Soap in 1998 you can root around the warehouse blow the dust of the tape and hope you did not throw away the tape drive to read it with.

Your accountants may have decided to retain monthly payroll data in the payroll system for seven years. So when the IRS demand to know how much you paid Joan Soap in March 2008 you can access the data with a normal query.


问:
Why is there no Swap command?
In many programming languages, I see programmers always struggle to swap 2 variabeles. Most of the time it costs 3 copies and a temporary variabele to accomplish it.

Why do programming language dont have build-in support for something basic like this?

答:
There are other methods for doing the same thing.  Some of which are more flexible, allowing rotation.

In Python:

```<code>x = 1
y = 2
z = 3
(x, y) = (y, x)
print x, y
(x, y, z) = (z, x, y)
print x, y, z
</code>```

Other languages allow similar behavior.

Title: Why is there no Swap command?

Body:
There are other methods for doing the same thing.  Some of which are more flexible, allowing rotation.

In Python:

x = 1
y = 2
z = 3
(x, y) = (y, x)
print x, y
(x, y, z) = (z, x, y)
print x, y, z

Other languages allow similar behavior.


问:
How would you design a user database with custom fields
This question is around how should I design a database, it can be relational / nosql databases, depending on what will be the better solution

Given a requirement where you'll need to create a system that will involve a database to track "Company" and "User". A single user always only belong to one company

A user can only belong to one company

A company can have many users

The design for "Company" table is quite straightforward.
Company will have the following attributes / columns: (let's keep it simple)

```<code>ID, COMPANY_NAME, CREATED_ON
</code>```

First scenario

Simple & straight forward, users all have the same attribute, so this can be easily done in relational style, user table:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CREATED_ON
</code>```

Second scenario

What happen if different companies want to store different profile attribute for their user. Each company will have a defined set of attributes that would apply to all users of that company.

For example:

Company A wants to store: LIKE_MOVIE (boolean), LIKE_MUSIC (boolean)

Company B wants to store: FAV_CUISINE (String)

Company C wants to store: OWN_DOG (boolean), DOG_COUNT (int)

Approach 1

the brute force way is to have a single schema for the user and let them have nulls when they dont belong to the company:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, LIKE_MOVIE, LIKE_MUSIC, FAV_CUISINE, OWN_DOG, DOG_COUNT, CREATED_ON
</code>```

Which is kinda nasty because you will end up with a lot of NULLS and user rows that have columns that are irrelevant to them (ie. all users belonging to Company A has NULL values for FAV_CUISINE, OWN_DOG, DOG_COUNT)

Approach 2

a second approach, is to have "free form field":

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_1, CUSTOM_2, CUSTOM_3, CREATED_ON
</code>```

Which would be nasty on its own since you have no idea what custom fields are, the data type will not be reflective of the values stored (eg. we'll store int value as VARCHAR).

Approach 3

I have looked into PostgreSQL JSON field, in which case you will have:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_PROFILE_JSON, CREATED_ON
</code>```

In this case, how would you be able to apply different schemas to a user?
A user with Company A will have schema that looks like

```<code> {"LIKE_MOVIE":"boolean", "LIKE_MUSIC": "boolean"}
</code>```

While a user with Company C will have a different schema:

```<code> {"OWN_DOG ":"boolean", "DOG_COUNT": "int"}
</code>```

How should I solve this issue? How can I design database properly to allow for this flexible schema for a single "object" (User) based on the relationship they have (Company)?

relational solution? nosql solution?

Edit: I've also thought about a "CUSTOM_PROFILE" table which will essentially store user attributes in rows rather than columns.

There are 2 problems with this approach:

1) The data grows per user grow as rows rather than columns - and this mean to get a full picture of the user, a lot of joins need to be done, multiple joins to the "custom profile" table on the different custom attributes

2) The data value is always stored as VARCHAR to be generic, even if we know the data is supposed to be integer or boolean etc

答:
My solution assume that you would be calling this query from a program and you should be able to perform post processing. You can have following columns:

```<code>ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_VALUES
</code>```

CUSTOM_VALUES will be of type string storing key and values pair. key will be column name and value will be column value e.g.

```<code>LIKE_MOVIE;yes;LIKE_MUSIC;no;FAV_CUISINE;rice
</code>```

in this CUSTOM_VALUES you will save only those information which exist.
When you query from program you can split this string and use it.

I've been using this logic and it works fine, its just that you will have to apply filtering logic in code and not in query.

Body:
My solution assume that you would be calling this query from a program and you should be able to perform post processing. You can have following columns:

ID, COMPANY_ID, FIRST_NAME, LAST_NAME, EMAIL, CUSTOM_VALUES

CUSTOM_VALUES will be of type string storing key and values pair. key will be column name and value will be column value e.g.

LIKE_MOVIE;yes;LIKE_MUSIC;no;FAV_CUISINE;rice

in this CUSTOM_VALUES you will save only those information which exist.
When you query from program you can split this string and use it.

I've been using this logic and it works fine, its just that you will have to apply filtering logic in code and not in query.


问:
Is it OK to use name like `CLASS_CONSTANT` for class constant variables according to PEPs? [python]
On the code I'm viewing, I saw a class like this:

```<code>class User(ModelBase):
    """# User: docstring"""

    COMBAT_RANK_KEY_PREFIX = 'combat_rank'
    LEVEL_RANK_KEY_PREFIX = 'level_rank'
    EQUIPMENT_RANK_KEY_PREFIX = 'equipment_rank'
    WORLD_REGAIN_RANK_KEY_PREFIX = 'world_regain_rank'
    COMMANDER_RANK_KEY_PREFIX = 'commander_rank'
    LIKE_RANK_KEY_PREFIX = 'like_rank'

    # Rest part of the class is omitted here
</code>```

There are other many class constant name like this in the project.

I consult PEP8 and saw no regulations for class constant.

Which only mentions golabl constant can use name like GLOBAL_CONSTANT.

But I still don't feel right to write a "class constant" like this,

but as they were wrote by my senior colleagues, I'm not sure if it's right or not.

So, is this kind of naming OK according to PEPs and Common rules?

答:
PEP 8 Allows you a bit of flexibility¸but requires consistency.  I would use underscored caps, as per your initial suggestion for all constants, since what will make them instantly recognizable and distinct from Class names and other variables.

So in short it is right.  But when working on a project where a different patterns are follow the pattern used in the project you are working on, unless you are willing to go through the entire project and update all the naming.


问:
Use interface or abstract class?
Now the title might seem like the question has been asked before but let me explain my situation and you'll see why I am asking this question.

Let's consider this interface :

```<code>public interface IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;
}
</code>```

If someone wants to implement this interface, they would have to check if ItemAdded is null and only if it is not null, they would call it. Well, I want to simplify their job by giving an in built function which will do the same. Just calling that function will check if the corresponding event is null, and if it isn't, it'll fire its corresponding event.

The problem is, this is an interface. So I can't define a method. So I thought I might go with an abstract class. But considering the situation, it would be best suited to make this as an interface rather than an abstract class.

So do I just drop the idea of giving an in built function? Or do I make it an abstract class? Which better suits the situation? I am having a tough time deciding which one to use. Some help please?

答:
What would be best is to have a mixin, but unfortunately C# doesn't include this concept. In the absence of mixins, I'd pick an interface over an abstract class almost every time, and definitely in this case. Whatever functionality has to be offered to derived classes, it can be offered in form of helper objects and utility functions. Favoring composition over inheritance is my favorite design principle.

In this specific case we should be able to have it both though. I would definitely have the interface, as you defined it. The interface should be used by all consumers and other classes in your utility. For the convenience of your users (developers) I would also have a default implementation of the interface that can be used as a base class.

```<code>public interface IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;
}

public class ListChangedListener : IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;

    public void FireItemAdded(...) {
        if (ItemAdded != null)
            ItemAdded(...)
    }

    public void FireItemRemoved(...) {
        if (ItemRemoved != null)
            ItemRemoved(...)
    }
}
</code>```

This way a developer can either derive from the ListChangedListener class, or implement the IListChangedListener interface directly, depending on circumstances. In the end of the day what counts is that the listener class they provide implements the IListChangedListener interface.

Would that work?

Title: Use interface or abstract class?

Body:
What would be best is to have a mixin, but unfortunately C# doesn't include this concept. In the absence of mixins, I'd pick an interface over an abstract class almost every time, and definitely in this case. Whatever functionality has to be offered to derived classes, it can be offered in form of helper objects and utility functions. Favoring composition over inheritance is my favorite design principle.

In this specific case we should be able to have it both though. I would definitely have the interface, as you defined it. The interface should be used by all consumers and other classes in your utility. For the convenience of your users (developers) I would also have a default implementation of the interface that can be used as a base class.

public interface IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;
}

public class ListChangedListener : IListChangedListener {
    public event EventHandler ItemAdded;
    public event EventHandler ItemRemoved;

    public void FireItemAdded(...) {
        if (ItemAdded != null)
            ItemAdded(...)
    }

    public void FireItemRemoved(...) {
        if (ItemRemoved != null)
            ItemRemoved(...)
    }
}

This way a developer can either derive from the ListChangedListener class, or implement the IListChangedListener interface directly, depending on circumstances. In the end of the day what counts is that the listener class they provide implements the IListChangedListener interface.

Would that work?


答:
Because you usually don't need it

Swapping the contents of two variables is a task that is mostly used at university or programming classes.

It's real-life use is limited to sorting algorithms and (maybe?) encryption. If you are writing a algorithm like this, you are probably capable of swapping two values anyway.

That being said, most programming languages don't have many things built in to begin with. A lot of the functions we use every day are part of some library or runtime environment. These functions are often added in an incremental way, but only if they solve issues users of the particular language or library had: It's all about demand.

Title: Why is there no Swap command?

Body:
In many programming languages, I see programmers always struggle to swap 2 variabeles. Most of the time it costs 3 copies and a temporary variabele to accomplish it.

Why do programming language dont have build-in support for something basic like this?


答:
In some languages, variables cannot be assigned (more than once, at their definition). In particular in functional languages like Ocaml (or Haskell) variables cannot be swapped (this would be meaningless).
In these languages mutable references or mutable fields are not the same as variables. And functional languages don't have commands or statements, but only expressions!</p>

Title: Why is there no Swap command?


问:
Layers of confusion (abstraction)
I have been assigned to a project where the end-product is a website as a music community. So it's uploading of music, sharing it amongst other users, listening to music from the website and so forth. It's a project that will not cross the borders of this nation, that's certain, so the scaling part is really not interesting.

At the moment we have ~12.000 users total, so it almost nothing.

That being said, for me it's a really simple and straightforward product. But we all know that simple can be ruined by a lot of things.

My problem with the codebase is the many obscure layers. We start of by loading a "shell" and from there we do like this:

HTML/AngularJs -> TypeScript -> Breeze -> WebApi/OData -> Entity Framwork

So really, my question is whether it's just me or if I am correct in my mind when I think this is totally over-architectured. And has someone else has seen an architecture like this and would you agree that cutting away the typescript + breeze abstraction would be the way to optimize the architecture ?

Having seen something like this I have lost some faith in TypeScript, because it is really hard for me not to see it just an abstraction between connecting some frontend framework and some backend framework, instead of them just "talking together" with TypeScript in the middle.

答:
It's dangerously easy as a programmer to start thinking that every project you encounter could and should be done better (read: rewritten) because it doesn't correspond to your vision. We've ALL been there.

You look at code and your mind just goes into "what's wrong with this"-mode, instead of focusing on what's right about it.

If you start plucking away at the components, how much time will you lose? Time you were assigned to spend on the actual assignment.

Do you have any guarantee that removing components X or replacing them with technology Y will increase performance, scalability, maintainability?

It seems to me that a web application of this nature could certainly benefit from most, if not all, components it appears to have: O/RM, caching strategy, strong typing, REST capabilities, some mobile-ready features, ...

The pertinent question is not "should this project be made up of components X, Y and Z but rather: was it well written? Does it make sound use of said components?

You didn't mention for how long you have been and will continue to be working on this project, but to me an architectural redesign or component swap-out should be a last resort after you have thoroughly examined the application, made it your proverbial home (and this preferably takes a lot of time and research), whereas it sadly tends to be out with the old, in with the new.

So, in the end, it's not up to us to decide but up to you. Just be careful that if you decide to go ahead and redesign / swap-out / rewrite, you do it for the right reasons.

Title: Layers of confusion (abstraction)


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

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

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

答:
Isn't it more reasonable to focus on studying stuff related to your direction? Or is there a reason you should spend some time to learn the low-level basics anyway?

Answer:

If you are not planning to change your direction to program embedded system there is no reason to learn assamble. Even thought that assembly is CPU depended you may learn some basics but your knowledge will be based on CPU architecture and instruction set for that CPU.

Let say you code for Windows. If want to learn lower level than high level language that may benefit you current direction, I would recommend you to learn Windows I deep, Windows API, Windows memory management etc. Simply learn the OS/Platform you are coding.

Improve your skills on your current high level language, such as memory management, garbage collection etc. If you want to go low level.


问:
Strategies for handling or avoiding race conditions
I'm working on a .NET application where I off-load my DB work (save operations) to a separate thread (inspired by how NodeJS handles IO operations). A save operation comes down to this (using Entity Framework):

```<code>public void Save(Customer customer)
{
    Task.Factory.StartNew(() =>
    {
        using (var entities = new MyEntities())
        {
            var persistedCustomer
                = entities.Customers.FirstOrDefault(x => x.Number == customer.Number);

            if (persistedCustomer == null)
            {
                persistedCustomer = new DBCustomer();
                // set properties
                entities.Customers.AddObject(persistedCustomer);
            }
            else
            {
                // set properties
            }

            entities.SaveChanges();
        }
    });
}
</code>```

So, in essence:

check if entity already exists in the DB

if not, create a new one

if it does already exist, update the existing one

Where this sometimes breaks down is when two calls to the Save method are made at the same time. Both threads see the entity doesn't exist yet and they want to do an insert. A standard race condition.

How would you go about fixing this? Any experience with this?

I could implement a retry mechanism, but was wondering if there are other options. A simple retry could of course overwrite certain properties that the previous save had updated.

答:
Problems like this are often solved with queues.

If you are saving same customer, you insert it into one ConcurrentQueue<T>. Then there is one thread that reads the queue sequentially and does the update on each item read. Only place where the synchronization between threads occurs is in insertion to the queue and that can be done both fast and without risk of deadlocks.


问:
Calculating the determinant of a matrix
I am working on a library (in my spare time) that I hope to open source soon. One of the elements in the library is a method for calculating the determinant of a given input matrix. For this, I have created a sub-project called "LUDecomposition" because I will use LU Decomposition in order to calculate the Determinant.

Now, my best approach was:

Have a class "LUDecomposition" which calculates the LU Decomposition of an input signal

Have another class "Determinant" which uses the LUDecomposition for the calculate and then returns this.

Currently, it is contained in one file, and, "Determinant" is inheriting from "LUDecompostion" but it does not look right, since, the relationship makes no sense. LUDecomposition -> CAN BE/IS A Determinant

But I cannot see any other option other than having a method inside the "LU Decomposition" and returning it from there. BUT the only problem is that, what if I did not want the users of the library/interface to know how the determinant is calculated?

```<code>#include <iostream>
#include <vector>

typedef std::vector<double> Vector;

namespace LUDecomposition {

    class LUDecompostion {

        public:

            LUDecompostion();

            template<typename Inverse>
            LUDecompostion(Inverse begin, Inverse end)
            : matrix_input(begin, end)
            {
                    const size_t matrix_size = matrix_input.size();

                    this->upper.resize(matrix_size, std::vector<double>(matrix_size));
                    this->lower.resize(matrix_size, std::vector<double>(matrix_size));
                    Solve();

            }

            void Solve();

            std::vector<Vector> getUpper();
            std::vector<Vector> getLower();

        protected:

            std::vector<Vector> matrix_input;
            std::vector<Vector> upper;
            std::vector<Vector> lower;

        };

        /*
                Class Determinant

        */

    class Determinant : public LUDecomposition {

        public:

            Determinant();

            template<typename Inverse>
            Determinant(Inverse begin, Inverse end)
            :   matrix_input(begin, end)
            {
                    /*
                            TO DO
                            TO DO
                            TO DO
                    */

            }

    };
}
</code>```

EDIT:

```<code>namespace LUP
{

    class LUPDecomposition {

        public:

            LUPDecomposition()
            {

            }

            string getLower()
            {
                return "This is the lower matrix";
            }

            string getUpper()
            {
                return "This is the upper matrix";
            }

        protected:

            std::vector<double> data;

    };

    LUPDecomposition FactorMatrix()
    {
        return LUPDecomposition();

    }
}
</code>```

答:
First, there is nothing wrong with your inheritance, although I would avoid naming the class Determinant; I would probably use LUP::Determinant and if compatibility with other objects is requested implement a IDeterminant interface (but in this specific case seems overkill). This is because your determinant is not a generic determinant but a specific implementation on top of a factorization. And I see no problem from having your determinant object reduced to the factorization it was computed from. There might be space and performance concerns though (if I need just the determinant why store everything else?).

With the namespace, I'd rather have a Decomposition namespace with LUP factorization, Cholesky factorization, QR factorization and so on. And note that you probably plan to do LUP not LU factorization so that should also be reflected.

Now, back to the factorizations, you probably do not want to have the solve which is the algorithm and the result which represents the data in the same object. For this you can:

Use generic functions and break inheritance and object dependencies

Can be implemented with functions or functor objects but the API should be something like:

```<code>LUP::Decomposition decomposition = LUP::FactorMatrix(matrix.begin(), matrix.end());
auto determinant = LUP::ComputeDeterminant(decomposition);
</code>```

where

LUP::FactorMatrix factors the matrix and returns the LU (or LUP) decomposition; this could be just a simple function (with template iterators)

LUP::Decomposition (or LU) contains the lower and upper triangular matrix and, if needed, the permutation matrix

LUP::ComputeDeterminant can be used on a various of inputs, and in this case an overload that works with a decomposition will return the matrix determinant. You can have it in a more generic namespace with an overload for LUP decomposition.

The advantage is that you can easily decide what data you store and you can also add other operations such as:

```<code>LUP::Decomposition decomposition = LUP::FactorMatrix(matrix.begin(), matrix.end());
if (LUP::ComputeDeterminant(decomposition) > 5) //whatever
    auto matrix = LUP::ComputeMatrixInverse(decomposition);
</code>```

Few other advantages:

Dependency injection is easy as long as you keep the interfaces compatible. You can have two Solve methods that behave differently (iterative?) but returns the same type of object so the process is the same.

There is no inheritance so adding functionality is as simple as creating a new function (functor)

You can even combine to a certain degree different algorithms from different methods

You control what is called, when it is called, what resources is each step using and so on. You can decide when to release the decomposition from memory and what to do with that.

You have a clear separation between your data and your algorithms which for such applications is a plus.

Title: Calculating the determinant of a matrix

Body:
First, there is nothing wrong with your inheritance, although I would avoid naming the class Determinant; I would probably use LUP::Determinant and if compatibility with other objects is requested implement a IDeterminant interface (but in this specific case seems overkill). This is because your determinant is not a generic determinant but a specific implementation on top of a factorization. And I see no problem from having your determinant object reduced to the factorization it was computed from. There might be space and performance concerns though (if I need just the determinant why store everything else?).

With the namespace, I'd rather have a Decomposition namespace with LUP factorization, Cholesky factorization, QR factorization and so on. And note that you probably plan to do LUP not LU factorization so that should also be reflected.

Now, back to the factorizations, you probably do not want to have the solve which is the algorithm and the result which represents the data in the same object. For this you can:

Use generic functions and break inheritance and object dependencies

Can be implemented with functions or functor objects but the API should be something like:

LUP::Decomposition decomposition = LUP::FactorMatrix(matrix.begin(), matrix.end());
auto determinant = LUP::ComputeDeterminant(decomposition);

where

LUP::FactorMatrix factors the matrix and returns the LU (or LUP) decomposition; this could be just a simple function (with template iterators)

LUP::Decomposition (or LU) contains the lower and upper triangular matrix and, if needed, the permutation matrix

LUP::ComputeDeterminant can be used on a various of inputs, and in this case an overload that works with a decomposition will return the matrix determinant. You can have it in a more generic namespace with an overload for LUP decomposition.

The advantage is that you can easily decide what data you store and you can also add other operations such as:

LUP::Decomposition decomposition = LUP::FactorMatrix(matrix.begin(), matrix.end());
if (LUP::ComputeDeterminant(decomposition) > 5) //whatever
    auto matrix = LUP::ComputeMatrixInverse(decomposition);

Few other advantages:

Dependency injection is easy as long as you keep the interfaces compatible. You can have two Solve methods that behave differently (iterative?) but returns the same type of object so the process is the same.

There is no inheritance so adding functionality is as simple as creating a new function (functor)

You can even combine to a certain degree different algorithms from different methods

You control what is called, when it is called, what resources is each step using and so on. You can decide when to release the decomposition from memory and what to do with that.

You have a clear separation between your data and your algorithms which for such applications is a plus.


问:
Should I always return an error code from C functions?
I have the following code in many places in a large application:

```<code>if (datastruct.data_ok &&
    cur_time > datastruct.start_time && cur_time < datastruct.end_time)
{
  do_something();
}
</code>```

Now, I wanted to eliminate repeated code by defining a function time_ok(...) which would simplify the repeated code to:

```<code>if (time_ok(&datastruct, cur_time))
{
  do_something();
}
</code>```

In my opinion, this is a well-made refactoring and should be therefore done. If the definition of the condition changes in the future, code maintenance becomes easier as only one location needs to be changed.

However, several team members noticed that the function can be abused by giving it a NULL argument, which crashes the program. They also complained that the return value is a boolean and not an error code, and all functions should according to them return an error code.

So, he refactoring would according to them be done in the following way:

```<code>bool time_ok_condition;
int err;
err = time_ok(&datastruct, &time_ok_condition, cur_time);
if (err != 0)
{
  fprintf(stderr, "Error %d at file %s line %d", err, __FILE__, __LINE__);
  exit(1);
}
if (time_ok_condition)
{
  do_something();
}
</code>```

However, in my opinion this results in excessively long code and if I really
have to do all this, I'd much rather have the original non-refactored code.

I invented a way around this rule by using a macro:

```<code>if (TIME_OK(datastruct, cur_time))
{
  do_something();
}
</code>```

...which can never crash the program on NULL arguments as the macro takes the structure name and not a pointer to the structure as the argument. However, I don't particularly like this approach of using a macro because the macro evaluates its arguments multiple times.

I noticed that although C was developed for Unix and Unix system calls traditionally return error codes, the standard C library functions such as strstr, strchr, strspn do not return an error code and therefore handle NULL arguments by crashing the program.

Now, it is an entirely different question whether the program should crash with coredump or print a meaningful error message for the theoretical error that never happens in this program (see the question How should “this can never happen” style of errors in C be handled? on Stack Overflow).

However, this question is about whether it should be allowed to return something else than an error code. A positive answer would in practice necessitate the use of "crash with coredump" strategy in this very specific case as the range of a boolean return cannot represent errors, but does not necessarily mean that a "crash with coredump" strategy is optimal in all cases.

Who is correct? Should C functions always return an error code like Unix system calls, or should it be allowed to write functions that return something else if there is justified reason for it such as code simplicity?

答:
The requirement for an error code arises from the fact the new function now can have 3 outcomes instead of 2: the time struct is ok, it is not ok, or the passed argument is NULL. The contract you have in mind for your function is "do not pass a NULL value in, otherwise the program will crash or show some undefined behaviour", whilst your coworkers believe programs become safer without such functions.

According to this former PSE post, and the topmost answer, the viewpoint of your coworkers is an extremely pedantic one, and in the context you have in mind the function will be called with something extremly unlikely to be NULL. Thus it will be most probably safe (maybe safer!) not to handle NULL by the return of an error code (as long as the program will crash or exit immediately with an error message, so it does not hide any severe error).

Of course, when your "time_ok" function is going to become part of a library, which might be reused in lots of different contexts (and maybe in a context where calling exit is not a good option), then it is indeed better to return an error code for the NULL argument to let the caller decide how to handle that problem.


问:
Algorithm for a UI showing X percentage sliders whose linked values always total 100%
A system I'm building includes a set of UI sliders (the number varies) each with a scale of 0-100. By slider I mean a UI where you grab an element and drag it up and down, like a volume control. They are connected by an algorithm that ensures they always total 100. So when one slider is moved up, the others all move down, eventually to zero. When one is moved down, the others move up. At all times the total must be 100. So here sliders have various values, but they total 100%:

```<code>----O------ 40
O----------  0
--O-------- 20
--O-------- 20
--O-------- 20
</code>```

If the first slider then moves UP from 40 to 70, the others have to move DOWN in value (as the slider is dragged). Note three sliders changed from 20 to 10, and one stayed at zero as it cannot go lower.

```<code>-------O--- 70
O----------  0
-O--------- 10
-O--------- 10
-O--------- 10
</code>```

Of course when any slider reaches 0 or 100, it cannot move any further, which is where my head really starts to hurt. So if a slider moves higher, the others move lower, but when any of them reach zero only the remaining ones that have not yet reached zero can move lower.

I'm asking this here as this question is specific to the algorithm not the implementation. FWIW the platform is Android Java, but that's not especially relevant.

The approach I took with my first stab was to calculate the percentage change of the slider that moved. I then split that change and applied it (in the other direction) to the other slider values. The problem though is that by using percentages and multiplying, if any slider gets to zero, it can never be increased again from zero - the net result of that is that individual sliders get stuck at zero. I've used sliders with a range of 0 - 1,000,000 to avoid rounding issues and that appears to be helpful, but I've yet to create an algorithm that handles all scenarios well.

答:
One simple technique is to calculate percentages of slider values relative to sum of slider values and then reassign the slider values to respective calculated percentages. this way slider values will be readjusted e.g

```<code>slider1.value = (slider1.value / sumOfSliderValues) * 100 ;
slider2.value = (slider2.value / sumOfSliderValues) * 100 ;
slider3.value = (slider3.value / sumOfSliderValues) * 100 ;
</code>```

Although it introduces round off error but it can be handled in case we need the sliders values to exactly and always sum up to 100.

I have setup a fiddle to demonstrate this using angularjs. Please visit demo

Body:
One simple technique is to calculate percentages of slider values relative to sum of slider values and then reassign the slider values to respective calculated percentages. this way slider values will be readjusted e.g

slider1.value = (slider1.value / sumOfSliderValues) * 100 ;
slider2.value = (slider2.value / sumOfSliderValues) * 100 ;
slider3.value = (slider3.value / sumOfSliderValues) * 100 ;

Although it introduces round off error but it can be handled in case we need the sliders values to exactly and always sum up to 100.

I have setup a fiddle to demonstrate this using angularjs. Please visit demo


问:
Do designer tools degrade the programming experience?
I've been looking around lately, specifically at some of the MS tools that are available, and I'm noticing a big focus on designer tools and wizards. Not just for UI development but for everything.

Entity Framework has the modeller

RIA Services has the DomainService wizard(s)

Workflow has the whole workflow designer thingy... (I don't know, haven't really used it)

There's more, but I think you get the idea. There's lots of designer tools. Using some of these I find that:

They complicate matters beyond the prescribed use cases

(ie all of the tech demo videos)

I have been evaluating some of these technologies recently, and trying to work with them I end up having to dissect exactly what the designers, modellers and wizards are doing for me... otherwise I'm lost when I actually have to try to do something with whatever was created.

This ends up being a case where I have to fight the tool, or fight its output enough such that I could have just done the whole thing myself without it - and had a much stronger understanding of what's going on. I find this particularly infuriating with the silverlight designer and RIA services domain service wizard.

I find myself asking "What good is this tool if I have to figure out its inner workings or re-write half of its output in order to use it?"

They're not as fast

The selling point of these tools is to increase productivity and this point may change over time using the tool, and doesn't necessarily apply to UI designers (though, in some cases it still does -> I'm looking at you silverlight designer). I find that I can hack some code much faster than I can drag-and-drop, resize, move, whatever in a designer.

The UI gets in the way of the model

Maybe this is just me, but when I am using anything reminiscent of a UML design tool I end up spending more time laying everything out so that my lines don't cross and so that I can see it all on the screen than modelling what I'm trying to achieve.

They're no fun

Half of the reason that I code for a living is that I enjoy it. Clicking checkboxes and selecting comboboxes and then fixing everything that comes out isn't fun.

I don't appear to be alone

The community seems to not want these tools either. The best example I can think of at the moment is Entity Framework Code-First.

So I ask:

Do designer tools actually improve productivity?

Are they fun-killers?

Is 'the community' actually asking for more designer tools, or are vendors just thinking we are?

答:
I think it probably depends.  If you are a fairly inexperienced developer then using the design tools probably is more productive than typing it out.  I'm fairly certain that I was more productive in my early VB6 days using the designer than I would have been cranking it out by hand.  The other thing to consider is how does the technology (at least how the IDE presents it) lend itself to hand editing.  VB6 and .NET WinForms certainly don't (or rather you probably don't want to hand edit the "generated" code file (or portion of).  With WPF and ASP.NET I think that a fairly inexperienced developer will start with the designer but quickly graduate to editing the XAML/ASP directly.  Once you know what you are doing it's certainly faster to edit the markup directly.  Thinking back to EF v1.0, I had to edit the XML backing the designer and it sucked, I never could wrap my brain around it so I kept falling back to the designer.

Depends on if the markup is fun to work with.  WPF and ASP(.NET) can be fun.  VB6/WinForms - nope don't want to edit the generated code sections more than necessary.

I don't think the community does explicitly.  Although when learning something new the designer can make it easier to swallow in chunks of learning.


问:
When and how to do a release?
Scenario

I have a plugin for CakePHP 3, which I am working on and people are submitting bugs for it. I have an active development branch in develop to which I send pull requests from fix branches.

I am using the semantic versioning standard for versioning my plugin.

When should I release?

If I have three open bugs and I fix them one after the other, should I be making three releases? Or should I make a single release for all of these fixes?

How do multiple fixes impact my versioning?

In the above example I have three fixed bugs, so to me that means I should be increasing the PATCH version number by three. Is that correct, or is the version number specifically tied to the release. So, by pushing a single release I would only increment the PATCH version by one to indicate one bugfix release?

TL;DR

Does each fix count towards your versions PATCH number?

答:
It's never explicitly spelled out, but careful reading of semver.org suggests that a version is associated with a proper release, not a VCS commit. So naturally, if you make one release that has multiple bug fixes, you increment the patch component once. Leaving large gaps to account for intermediate states that don't have a version (not even in principle, like broken releases that have been withdrawn) makes no sense.

You could of course make a release for every single tiny change, but this is probably not desirable: It's a lot of work for you, it wastes user's time and bandwidth with frequent updates, and it results in ludicrous version numbers and release logs. There are various policies for when to release, and which works best is mostly a matter of opinion and the quirks of the project and its user base. Some common options are:

Some project release once every X time units, regardless of how many or few changes were done.

Some projects release once a subjective threshold of "enough changes" is reached.

Some projects have milestones: "We'll release vX.Y once we have this thing and that thing done".

A mix of the above.

Most projects, even when they normally adhere to one of the above, can release out-of-line hot fixes when a particular nasty bug was released in the wild.

Conversely, if you put out new releases so rarely (or never) that most people just track git master, then you fail at semver because these people don't get any backwards compatibility guarantees. The fix is not to give each commit its own version number but to release in more sensible intervals.

Title: When and how to do a release?


答:
Beware that if CakePHP 3 is changing its plugin API (and your plugin adapts to that change), you probably should increase your major number.

BTW, in MELT I am explicitly naming the version(s) of GCC for which that release is made. So I am naming them MELT-1.1.3 for GCC 4.8 or 4.9

Plugins are a corner-case of semantic versioning, because what usually matters is both the version of the plugin, and the (acceptable) version of the program using that plugin.

Title: When and how to do a release?

Body:
Scenario

I have a plugin for CakePHP 3, which I am working on and people are submitting bugs for it. I have an active development branch in develop to which I send pull requests from fix branches.

I am using the semantic versioning standard for versioning my plugin.

When should I release?

If I have three open bugs and I fix them one after the other, should I be making three releases? Or should I make a single release for all of these fixes?

How do multiple fixes impact my versioning?

In the above example I have three fixed bugs, so to me that means I should be increasing the PATCH version number by three. Is that correct, or is the version number specifically tied to the release. So, by pushing a single release I would only increment the PATCH version by one to indicate one bugfix release?

TL;DR

Does each fix count towards your versions PATCH number?


问:
Is creating the objects you think you will need ok in a first test in TDD
I'm fairly new to TDD and I have trouble when creating my first test when it comes before any of the implementation code. Without any framework to the implementation code I am free to write my first test however I want but it always seems to come out tainted by my Java / OO way of thinking about the problem.

For example in my Github ConwaysGameOfLifeExample the first test I wrote (rule1_zeroNeighbours) I started out by creating a GameOfLife object that hadn't been implemented yet; called a set method that didn't exists, a step method that didn't exist, a get method that didn't exist, and then used an assert.

The tests evolved as I wrote more tests and refactored, but originally it looked something like this:

```<code>@Test
public void rule1_zeroNeighbours()
{
    GameOfLife gameOfLife = new GameOfLife();
    gameOfLife.set(1, 1, true);
    gameOfLife.step();
    assertEquals(false, gameOfLife.get(1, 1));
}
</code>```

This felt odd as I was forcing the design of the implementation based on how I had decided at this early stage to write this first test.

In the way that you understand TDD is this ok? I seem to be following the TDD / XP principles in that my tests and implementation evolved over time with refactoring, and so if this initial design had proved useless it would have been open to change, but it feels like I am forcing a direction on the solution by starting this way.

How else do people use TDD? I could have gone through more iteration of refactoring by starting out with no GameOfLife object, only primitives and static methods but that seems too contrived.

答:
There different  school of thought about this.

Some say: test not compiling is error - go fix write smallest available production code.

Some Say: it is OK to write test first check if it sucks(or not) ant then create missing classes/methods

With first approach you are really in a red-green-refactor cycle.
With second you have a little bit wider overview what you want to achieve.

It is up to you to choose which way you work. IMHO both approaches are valid.


答:
Even when I implement something in a "hack it together" way, I still think up the classes and steps that will be involved in the whole program. So you've thought this through and written these design thoughts down as a test first - that's great!

Now keep iterating through both implementation to fulfill this initial test, and then add more tests to improve and extend the design.

What might help you is to use Cucumber or similar to write your tests in.

Title: Is creating the objects you think you will need ok in a first test in TDD

Body:
I'm fairly new to TDD and I have trouble when creating my first test when it comes before any of the implementation code. Without any framework to the implementation code I am free to write my first test however I want but it always seems to come out tainted by my Java / OO way of thinking about the problem.

For example in my Github ConwaysGameOfLifeExample the first test I wrote (rule1_zeroNeighbours) I started out by creating a GameOfLife object that hadn't been implemented yet; called a set method that didn't exists, a step method that didn't exist, a get method that didn't exist, and then used an assert.

The tests evolved as I wrote more tests and refactored, but originally it looked something like this:

```<code>@Test
public void rule1_zeroNeighbours()
{
    GameOfLife gameOfLife = new GameOfLife();
    gameOfLife.set(1, 1, true);
    gameOfLife.step();
    assertEquals(false, gameOfLife.get(1, 1));
}
</code>```

This felt odd as I was forcing the design of the implementation based on how I had decided at this early stage to write this first test.

In the way that you understand TDD is this ok? I seem to be following the TDD / XP principles in that my tests and implementation evolved over time with refactoring, and so if this initial design had proved useless it would have been open to change, but it feels like I am forcing a direction on the solution by starting this way.

How else do people use TDD? I could have gone through more iteration of refactoring by starting out with no GameOfLife object, only primitives and static methods but that seems too contrived.


答: You mean like InterlockedExchange or like STL's swap, though neither are language specific STL is close enough.</p>

Title: Why is there no Swap command?


答:
In order to write the test in the first place, you have to design the API that you are then going to implement. You've already started on the wrong foot by writing your test to create the entire GameOfLife object and using that to implement your test.

From Practical Unit Testing with JUnit and Mockito:

At first you might feel awkward for writing something which is not even there. It requires a slight change to your coding habits, but after some time you will come to see it is a great design opportunity. By writing tests first, you have a chance of creating an API that is convenient for a client to use. Your test is the first client of a newly born API. This is what TDD is really all about: the design of an API.

Your test doesn't make much of an attempt to design an API. You have set up a stateful system where all the functionality is contained within the outer GameOfLife class.

If I were to write this application, instead I would think about the pieces I want to build. For example, I might make a Cell class, write tests for that, before moving on to the larger application. I would certainly create a class for the "infinite in every direction" data structure that is required to properly implement Conway, and test that. Once all of that was done, I would think about writing the overall class that has a main method and so forth.

It's easy to gloss over the "write a test that fails" step. But writing the failing test that works the way you want it to is the core of TDD.


答:
Before you start writing your tests, you should think about how to design your system. You should spend some considerable amount of time during your designing phase. If you did it, you won't get this confusion over TDD.

TDD is just a development approach link: TDD

1. Add a test

2. Run all tests and see if the new one fails

3. Write some code

4. Run tests

5. Refactor code

6. Repeat

TDD helps you to cover all the required features what you have planned before you start developing your software. link: Benefits


问:
eBook editions of programming books
(I'll get my justification for why this is on topic in early: programming books tend to have fairly specific formatting needs - code samples, tables, images and graphs - which are not common to all book types and are not necessarily well handled by eBook readers.  Similarly they're used in different ways - you often dip in and out rather than read cover to cover.)

I've just noticed that Don't Make Me Think by Steve Krug is available as an eBook edition for the Kindle (and presumably also for other readers) which set me thinking.

There are certain advantages to eBook readers for tech books - primarily that you can carry a massive library of what would be heavy physical books around very easily.  The downside is that certain eBook readers allegedly aren't particularly well equipped to cope with tables, code samples and so on and a book like Don't Make Me Think presumably makes extensive use of these sorts of things.

So, the question, what are your experiences of reading and using programming books on an eBook reader and would you recommend it? I'm specifically interested in the latest generation Kindle but happy to hear about all devices - might be useful to state which one you use in the answer.

答:
Looking at the other answers, I see a lot of issues I've never come across when reading ebooks. I don't know if it's the ebooks I get, the readers I use, or the platforms I use, but I know I get much better results.

[Aside: I have the Kindle, iBooks, and Google Books apps on both my iPhone and iPad. Given a choice, though, I use the freeware app Stanza, which is simply amazing.]

Why I think tech ebooks are going to be around for the long haul:

I'm expecting that, in the not-too-distant future, some colleges and universities will require their students to have iPads (or a similar devices). I think that higher-ed will have required texts available as ebooks both for purchase and as one-term rentals (most-likely scenario: rental with an option to buy at the end of the term).

I remember how, as a student, I had to buy and cart around a massive pile of books every quarter—and then try to re-sell them afterwards.  I would have loved to have been able to have one slim device to carry around with me instead of all those bricks. And that's not even mentioning the standing in lines at the student bookstore, swearing when the book I had to have was already sold out, or dealing with plummeting resale values—all of which will then be history.

You can't over-estimate the percentage of tech books that get sold into the education market.

Being able to annotate ebooks is great. Yes, I know I can do this on paper, but I never seem to have a pen/pencil around when I want one. And now I don't run out of room in the margins!

With the Kindle app, I can be reading an ebook on my iPhone, and then come back home to my iPad and start reading right where I left off. The annotations go with me as well. I also like the "popular highlights," which are annotations shared (anonymously) with others reading the same ebook. This is a very useful feature for tech books—if you're having trouble with an author's explanation of a topic, someone else may have annotated it for themselves with a clarification.

While there are some poorly-formatted ebooks (tech and otherwise) out there, as time goes on, formatting is only going to get better and better. Part of the reason for the poor formatting is that publishers don't yet have a lot of ebook experience; over time, they'll either learn or get out of the business.

Title: eBook editions of programming books


问:
How to define complex business rules using User Stories?
A quick and dirty definition of User Story:

```<code>"As a <role>, I want <goal/desire> so that <benefit>"
</code>```

In this commonly accepted definition there is little space for defining business rules, constraints or user input.

Trivial example just to illustrate:

```<code>"As a <librarian>, I want to <register new books> so that
<students can find their availability online>"
</code>```

In this silly example, where would one define the fields needed when registering a book? Should it be written anywhere? Or should the required business rules be passed as word of mouth by the Product Owner?

答:
In the example given, there are many details of book registration that developers migt know little about, such as Dewey or other classification systems, ISBNs, acquisition numbers, duplicate copies/titles/authors, other editions, and so on.  For a new system, such details must be provided by the customer (and a librarian, of all people, will certainly care about them).

To quote Steve O'Connell, "It's terrifying to contemplate how much business policy is created by developers who lacked the necessary detail in specifications so just made it up for themselves."


答:
This felt odd as I was forcing the design of the implementation based on how I had decided at this early stage to write this first test.

I think this is the key point in your question, Whether or not this is desirable depends on whether you lean towards codeninja's idea that you should design up-front then use TDD to fill in the implementation, or durron's idea that tests should be involved in driving out the design as well as the implementation.

I think which of these you prefer (or where you fall in the middle) is something you need to discover for yourself as a preference. It's useful to understand the pros and cons of each approach. There are probably plenty, but I'd say the main ones are:

Pro Upfront Design

However good a process TDD is at driving design, it's not perfect. TDing without a concrete destination in mind can sometimes run down dead ends, and at least some of these dead ends could have been avoided with a bit of upfront thinking about where you want to end up. This blog article makes this argument using the example of the Roman Numerals kata, and has a rather nice final implementation to show for it.

Pro Test-Driving Design

By building your implementation around a client of your code (your tests), you get YAGNI-adherence pretty much for free, as long as you don't start writing unneeded test cases. More generally, you get an API which is designed around its use by a consumer, which is ultimately what you want.

The idea of drawing a bunch of UML diagrams before writing any code then just filling in the gaps is nice, but rarely realistic. In Steve McConnell's Code Complete, design is famously described as a "wicked problem"- a problem you can't fully understand without first at least partially solving it. Couple this with the fact that the underlying problem itself may change through changing requirements, and this model of design starts to feel a bit hopeless. Test driving allows you to just bite off one chunk of work at a time- in design, not just implementation- and know that at least for the lifespan of turning red to green, that task will still be up to date and relevant.

As for your particular example, as durron says, if you did go with an approach of driving out the design by writing the simplest test, consuming the minimal interface it can, you probably would start with a simpler interface than the one in your code snippet.