问:
Translate MATLAB expressions containing "^" power operator to C++ syntax
Brief:
I have several very large math expressions written in Matlab/Octave syntax. I
want to evaluate them within a C++ function by copy and pasting them in, however the problem is they contain "^" operators that cannot be overloaded to work with doubles.

Details:
The expressions consist of scalar variables with nested trigonometric functions, addition and multiplication operators and power operators "^". There are so many expressions that it is not practical to manually edit them to be C++ compatible. The main problem arises with the power operator "^" which is reserved in C++ for the bitwise exclusive OR operation. I am developing this code to run on Ubuntu 14.04 LTS with gcc version 4.9.2.

I am asking for advice on how to proceed/comments on the following three ideas:

1) Write a new class that consists of "double-like" variables and an overloaded "^" operator, as well as "+,*,-" operators and trig functions.

2) Write some code to parse the MATLAB expressions, find each "^" character, identify the base term "a" and the exponent term "b" and replace them with the pow(a,b)

3) Look for some package online that has already done #1.

Backstory:
I am porting a large optimization code that originally used Mathematica to evaluate gradients, jacobians, etc. These Mathematica expressions were converted to Matlab using the ToMatlab[] package:
http://library.wolfram.com/infocenter/MathSource/577/
I now have a need to re-write the whole thing in C++.

There are hundreds of expressions similar to:

```<code> grad_out(1,1) = k1^(-1)*k2^(-1)*(k1*k2*(r+(-1)*R)*cos(b1*k1)+(-1)*
        k1^2*R*cos((b1+g1)*k1)+k1*k2*R*cos((b1+g1)*k1)+(-1)*
        k1^2*r*cos((b1+g1)*k1+g1*k2)+k1^2*R*cos((b1+g1)*k1+g1*
        k2)+k1^2*r*cos((b1+g1)*k1+(b2+g1)*k2)+(-1)*k1^2*k2*L*
        sin((b1+g1)*k1));
</code>```

答:
C# has pretty powerful regular expressions, you could make a command line program or something else...

This in C# uses Balanced Grouping Expressions to match parens:

```<code>namespace ConsoleApplication13
{
    class Program
    {
        static void Main ( string [] args )
        {
            const string identifier = @"[a-zA-Z0-9_]+";

            string expression = @"grad_out(1,1) = (k1*(2+(3))*k2)^(-1)+k3^(k2+1)+(k4)^(-1)+k5^(k6^k7);";

            System.Console.WriteLine ( expression );
            System.Console.WriteLine ( "\r\n=\r\n" );

            var regExString = @"(?<left>(" + identifier + @")|(((?<L0>\()[^()]*)+([^()]*(?<-L0>\)))+))" + @"\^" + @"(?<right>(" + identifier + @")|(((?<L1>\()[^()]*)+([^()]*(?<-L1>\)))+))";
            var re = new System.Text.RegularExpressions.Regex ( regExString );

            bool changed;
            do
            {
                var nextExpression = re.Replace ( expression, @"pow(${left},${right})" );
                changed = nextExpression != expression;
                expression = nextExpression;
            } while ( changed );

            System.Console.WriteLine ( expression );
        }
    }
}
</code>```

Output:

```<code>grad_out(1,1) = pow((k1*(2+(3))*k2),(-1))+pow(k3,(k2+1))+pow((k4),(-1))+pow(k5,(pow(k6,k7)));
</code>```

See also https://stackoverflow.com/q/7898310/471129,
and https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx

Body:
C# has pretty powerful regular expressions, you could make a command line program or something else...

This in C# uses Balanced Grouping Expressions to match parens:

namespace ConsoleApplication13
{
    class Program
    {
        static void Main ( string [] args )
        {
            const string identifier = @"[a-zA-Z0-9_]+";

            string expression = @"grad_out(1,1) = (k1*(2+(3))*k2)^(-1)+k3^(k2+1)+(k4)^(-1)+k5^(k6^k7);";

            System.Console.WriteLine ( expression );
            System.Console.WriteLine ( "\r\n=\r\n" );

            var regExString = @"(?<left>(" + identifier + @")|(((?<L0>\()[^()]*)+([^()]*(?<-L0>\)))+))" + @"\^" + @"(?<right>(" + identifier + @")|(((?<L1>\()[^()]*)+([^()]*(?<-L1>\)))+))";
            var re = new System.Text.RegularExpressions.Regex ( regExString );

            bool changed;
            do
            {
                var nextExpression = re.Replace ( expression, @"pow(${left},${right})" );
                changed = nextExpression != expression;
                expression = nextExpression;
            } while ( changed );

            System.Console.WriteLine ( expression );
        }
    }
}

Output:

grad_out(1,1) = pow((k1*(2+(3))*k2),(-1))+pow(k3,(k2+1))+pow((k4),(-1))+pow(k5,(pow(k6,k7)));

See also https://stackoverflow.com/q/7898310/471129,
and https://msdn.microsoft.com/en-us/library/az24scfc%28v=vs.110%29.aspx


ContentLicense: CC BY-SA 3.0

Title: Translate MATLAB expressions containing "^" power operator to C++ syntax

Body:
Brief:
I have several very large math expressions written in Matlab/Octave syntax. I
want to evaluate them within a C++ function by copy and pasting them in, however the problem is they contain "^" operators that cannot be overloaded to work with doubles.

Details:
The expressions consist of scalar variables with nested trigonometric functions, addition and multiplication operators and power operators "^". There are so many expressions that it is not practical to manually edit them to be C++ compatible. The main problem arises with the power operator "^" which is reserved in C++ for the bitwise exclusive OR operation. I am developing this code to run on Ubuntu 14.04 LTS with gcc version 4.9.2.

I am asking for advice on how to proceed/comments on the following three ideas:

1) Write a new class that consists of "double-like" variables and an overloaded "^" operator, as well as "+,*,-" operators and trig functions.

2) Write some code to parse the MATLAB expressions, find each "^" character, identify the base term "a" and the exponent term "b" and replace them with the pow(a,b)

3) Look for some package online that has already done #1.

Backstory:
I am porting a large optimization code that originally used Mathematica to evaluate gradients, jacobians, etc. These Mathematica expressions were converted to Matlab using the ToMatlab[] package:
http://library.wolfram.com/infocenter/MathSource/577/
I now have a need to re-write the whole thing in C++.

There are hundreds of expressions similar to:

```<code> grad_out(1,1) = k1^(-1)*k2^(-1)*(k1*k2*(r+(-1)*R)*cos(b1*k1)+(-1)*
        k1^2*R*cos((b1+g1)*k1)+k1*k2*R*cos((b1+g1)*k1)+(-1)*
        k1^2*r*cos((b1+g1)*k1+g1*k2)+k1^2*R*cos((b1+g1)*k1+g1*
        k2)+k1^2*r*cos((b1+g1)*k1+(b2+g1)*k2)+(-1)*k1^2*k2*L*
        sin((b1+g1)*k1));
</code>```

Body:
Matlab's symbolic toolbox can generate C code from a matlab expression using ccode:

syms b1 b2 g1 g2 k1 k2 L r R x1
ccode(k1^(-1)*k2^(-1)*(k1*k2*(r+(-1)*R)*cos(b1*k1)+(-1)*k1^2*R*cos((b1+g1)*k1)+k1*k2*R*cos((b1+g1)*k1)+(-1)*k1^2*r*cos((b1+g1)*k1+g1*k2)+k1^2*R*cos((b1+g1)*k1+g1*k2)+k1^2*r*cos((b1+g1)*k1+(b2+g1)*k2)+(-1)*k1^2*k2*L*sin((b1+g1)*k1)))

Outputs

t0 = -(-(k1*k1)*r*cos(k1*(b1+g1)+k2*(b2+g1))-R*(k1*k1)*cos(g1*k2+k1*(b1+g1))+(k1*k1)*r*cos(g1*k2+k1*(b1+g1))+R*(k1*k1)*cos(k1*(b1+g1))+L*(k1*k1)*k2*sin(k1*(b1+g1))+k1*k2*cos(b1*k1)*(R-r)-R*k1*k2*cos(k1*(b1+g1)))/(k1*k2);


问:
Is it odd if Nodes in a LinkedList held references to the List object?
Its like, I want to call .moveToBefore(Node) on a Node object and have the node relocate to before the node passed in.

The problem arises if the node passed in is the head node. The List object will still reffer to the old head where as the old head will actually follow the new head further down the chain.

I guess this could be solved easily if the nodes held a reference to the List object. So want to know if there are any disadvantages if the node objects in a Linked List implementation held a reference to its parent "List" object.

答:
To me the biggest problem is:

Increasing the size of a list node by an extra pointer (or references) for SLL, 3 for DLL. This might not affect performance that much if you're just sporadically allocating list nodes all over the memory space, since at that point it wouldn't matter much unless the node was just around 64 bytes, e.g., aligned to 64 byte boundaries, and the extra pointer made it over 64 bytes, in which case we would double up our cache misses. If you're using a careful allocation strategy, the smaller the list node, the better for sequential traversal, and one extra pointer might be a huge relative size increase just from the list POV.

The biggest real-world benefit of linked lists even in performance-critical areas is often that ability to move nodes from one list to another, split lists into two lists and merge them in constant time, etc. You complexify this part in exchange for simplifying something that isn't that complex.

Circular references were mentioned, and that might be a problem in some languages. If it's like C or C++, it would be a backpointer to the list which wouldn't affect collection in any way, the nodes would still be destroyed when requested.

What I recommend is to stop trying to put your linked list implementation into a node. Make a node raw data, a private implementation detail of a list that doesn't bother to provide much logic at all. Your life will generally become a lot easier if you stop trying to split functionality concerns too much between linked structures and their nodes: tree vs. tree node, linked list vs. list node, e.g. Put all the logic into the data structure where you have all the information you need to do everything (both head pointer and node). moveToFront should be a linked list method rather than list node method. With that, there's no more need for a backpointer.

```<code>class DataStructure
{
public:
    ...

private:
    struct Node
    {
        // Don't put functionality here except maybe a ctor/dtor at
        // most if you can avoid it. The distribution of concerns should
        // this node have functionality will often make things more
        // complex rather than simpler, and also have you reaching for
        // backpointers quickly, potentially wanting to waste memory
        // and increase the amount of state to maintain superfluously
        // (more state usually means more potential for bugs) just
        // because we want to put functions into this Node class.
    };
    ...
    Node* head_or_root;
};
</code>```

Another minor thing worth noting is that there's not really much smarter work that moveToFront can do besides erase and push to front, so it might not be worth having the extra function at all except as a convenience sort of thing.

That is, unless this is unavoidable, where the clients would only have a node that they access from a previously cached, persistent space, e.g., and no access to the linked list. If they do have access to the linked list, then the easiest way is just avoid putting logic into your nodes outright, and make them private, raw data C-style struct type of things.

Even then, you will often make your life easier in this case to simply require clients to store a reference to both node and linked list, instead of always storing a backpointer in a node (which may not be needed by most operations, making us waste memory often in places that don't benefit from this).

Another thing is that since Node models implementation details of a linked list, if you can avoid exposing Node references directly and instead provide some indirect handle to it, like Iterator, it'll reduce the risk of problems.

Body:
To me the biggest problem is:

Increasing the size of a list node by an extra pointer (or references) for SLL, 3 for DLL. This might not affect performance that much if you're just sporadically allocating list nodes all over the memory space, since at that point it wouldn't matter much unless the node was just around 64 bytes, e.g., aligned to 64 byte boundaries, and the extra pointer made it over 64 bytes, in which case we would double up our cache misses. If you're using a careful allocation strategy, the smaller the list node, the better for sequential traversal, and one extra pointer might be a huge relative size increase just from the list POV.

The biggest real-world benefit of linked lists even in performance-critical areas is often that ability to move nodes from one list to another, split lists into two lists and merge them in constant time, etc. You complexify this part in exchange for simplifying something that isn't that complex.

Circular references were mentioned, and that might be a problem in some languages. If it's like C or C++, it would be a backpointer to the list which wouldn't affect collection in any way, the nodes would still be destroyed when requested.

What I recommend is to stop trying to put your linked list implementation into a node. Make a node raw data, a private implementation detail of a list that doesn't bother to provide much logic at all. Your life will generally become a lot easier if you stop trying to split functionality concerns too much between linked structures and their nodes: tree vs. tree node, linked list vs. list node, e.g. Put all the logic into the data structure where you have all the information you need to do everything (both head pointer and node). moveToFront should be a linked list method rather than list node method. With that, there's no more need for a backpointer.

class DataStructure
{
public:
    ...

private:
    struct Node
    {
        // Don't put functionality here except maybe a ctor/dtor at
        // most if you can avoid it. The distribution of concerns should
        // this node have functionality will often make things more
        // complex rather than simpler, and also have you reaching for
        // backpointers quickly, potentially wanting to waste memory
        // and increase the amount of state to maintain superfluously
        // (more state usually means more potential for bugs) just
        // because we want to put functions into this Node class.
    };
    ...
    Node* head_or_root;
};

Another minor thing worth noting is that there's not really much smarter work that moveToFront can do besides erase and push to front, so it might not be worth having the extra function at all except as a convenience sort of thing.

That is, unless this is unavoidable, where the clients would only have a node that they access from a previously cached, persistent space, e.g., and no access to the linked list. If they do have access to the linked list, then the easiest way is just avoid putting logic into your nodes outright, and make them private, raw data C-style struct type of things.

Even then, you will often make your life easier in this case to simply require clients to store a reference to both node and linked list, instead of always storing a backpointer in a node (which may not be needed by most operations, making us waste memory often in places that don't benefit from this).

Another thing is that since Node models implementation details of a linked list, if you can avoid exposing Node references directly and instead provide some indirect handle to it, like Iterator, it'll reduce the risk of problems.


问:
Should you charge clients hours spent on the wrong track?
I took up a small CSS challenge to solve for a client and I'm going to be paid on a hourly rate.
I eventually solved it, it took 5 hours but I spent roughly 25% of the time in the wrong track, trying a CSS3 solution that only worked in recent browsers and finally discovering that no fallback is possible via JS (like I originally thought). Should I charge the client that 25%?

More details:
I didn't provide an estimate, I liked the challenge per se, so I started working on it before giving an estimate (but I have worked with him before, so I know he's not one of those people that have unrealistic expectations). At the very worst I will have spent 5 unpaid hours on an intriguing CSS challenge. And I will give the fairest possible estimate for both of us, since I will have already done the work. :)

Edit:
Thank you all, I wish I could accept more than one answer! I ended up not billing him for the extra hours (I billed him for 3 and a half), but I mentioned them, so that he knows I worked more on it than I billed him for. Maybe that's why he immediately accepted the "estimate" (which in that case wasn't an estimate, hence the quotes).

答:
I normally wouldn't charge if it was blatantly my fault and I was just jerking around, but I'm not business-smart at all. I have found most business-smart people apply this philosophy that clients are paying for their time, and not merely an end result. There are many times in my career where, in retrospect, I regretted not thinking this way. All I thought about was end result as having worth, my time being meaningless unless it improved the end result. Yet one could be dragged around and have a lot of time wasted as a result of clients changing their mind, of co-workers causing bugs that get assigned to you and delaying your work, e.g., and not merely because you needed a little more research upfront to really know what you were doing.

When you start bending the rules and making exceptions to what sort of working time should be paid for and what should be free of charge, it can be easy to eventually get taken advantage of. Time is the easiest metric to use for payment. It frees you of a lot of complex liability, which might seem irresponsible, but it protects you from being being pulled around and having the client's irresponsibility lead to some pay cut.

In my case, it would be hopeless if I couldn't charge for going down the wrong path, as I often work on things like this:

... trying to beat a nearly 40-year old Catmull-Clark subdivision algorithm that has been entrenched in the industry and improved repeatedly by companies like Microsoft and Pixar by trying to provide more intuitive results while still being just as competitive as these huge companies speed-wise.

95% of the time in such cases, I'm going down the wrong route, constantly going back to the whiteboard after failure after failure after failure. If I couldn't charge for my failures, I'd be homeless already. I see more than half of my work as research, when no one has tried these things ever before, and there's no way I could just find the perfect approach to tackle a solution on the very first try (maybe 20th try). To me the goal has never been to succeed on the first try but to fail as soon as possible, with each failure after failure providing some clues as to what that correct solution, which might actually be capable of changing the world, might be.

Not everyone might be working in such an R&D-intensive area where the customers want and expect you to beat the most well-established techniques out there simply because you're starting a fresh project, but to me programming is never quite routine no matter how simple and established a solution is. How you design and integrate parts will still be unique, always some form of art in itself yielding unique pros and cons, not mechanical, not perfectly scientific, otherwise robots could do it. So I think inevitably we'll always have to charge for going down some wrong routes here and there, or else we would only be able profit from the most routine work that we've done a hundred times already for which we apply the exact same solution each time, in which case we would be charging for hitting the copy and paste button.

Unpredictability

Another thing is that programming is always hard, unpredictable, never quite routine. It's not like pizza delivery which is routine, where all but something like a car accident can be accounted for (I unfortunately worked under a boss one time who equated programmer estimates to pizza delivery estimates and thought the only work we were actually doing was typing). It's learning on the site, always -- I can't imagine it ever becoming fully routine unless someone actually repeatedly paid me to implement like a quicksort over and over. There's always going to be some experimentation and learning going on there, and as long as it's not excessive, no need to feel guilty about it.

I've often dreamed of becoming a farmer or something just so that I could find a lot more routine motions in my work, not always pushing the boundaries of my existing knowledge. Instead I try to compensate by making my life outside of work as routine and as mundane as possible, to add some predictability and routine motions somewhere for the sake of sanity, which makes me a bore among people who want to find excitement in their lives outside of work -- I find plenty enough at work.

He's talking about learning new things, not working on the wrong
  solution.

Working on the wrong solution is learning new things, is it not? Did you know it was a wrong solution when you started, or did you keep persistently working on it even after you knew it was hopelessly wrong? Hopefully not the latter. Often the process of learning is through mistakes. It's the best teacher. The most effective strategy I've found is to just make mistakes as soon as possible, to discover that they are, indeed, design mistakes as soon as possible before we commit everything to them and marry such solutions, since the only constant I can count on and predict with near 100% certainty is that mistakes will be made. They're only expensive if they're discovered really late.

ContentLicense: CC BY-SA 2.5


问:
Should I write automated unit tests that fail when the code changes?
Generally when writing automated unit tests (eg JUnit, Karma)  I aim to:

cover all the boundary conditions

get a high level of coverage.

I heard someone say:

coverage and boundary conditions aren't enough for a unit test, you need to write them so they will break if the code changes.

This sounds good to me in theory - but I'm not sure how to apply it.

My question is: Should I write automated unit tests that fail when the code changes? If so, how.

答:
The answers given - that this is a wrongheaded thing to do, and violates every principle of good testing - are correct.

But this is programming. There are always some sensible rationales for even the strangest request, and it can be productive to consider them.

Say you have some critical kernel code, or some high-security part of your SSH library, which absolutely, under no circumstances, should ever change its behavior, not even for some tiny subset of the infinite values it takes, all of which you could never test against.

And say you have a company set up such that there is a QA department responsible for writing unit tests against code provided by the Dev deparment, to ensure it meets business requirements.

In this situation, it makes sense to say "the critical code paths should only be modified by Dev when QA has been notified with signoff by upper management." Any change without signoff and notification is non-deliberate, and may be malicious.

In that case, a test which uses introspection to get a hash of the contents of each method, and compare that to a stored hash, could be legitimate. You can't serialize Method(), but you could subclass Method to be serializable. Perhaps a better approach is to get a hash of the file itself. Or just compare the file to a secure backup of the file.

But probably the best approach if the requirement is to fail on any modification, is to check the versioning system's logs and see if any changes were downloaded for the relevant files. If yes, then fail.


问:
Event Driven Programming: A sequence of unfortunate events
I have a very basic game loop whose primary purpose is to check for updates & changes to a list.

I have contemplated using event driven programming to replace the game loop/list idea with an ObservableCollection, however I just have this big cloud of doubt on event driven programming.  I'm posing these questions to those with experience with event driven programming:

What are good ways to test & build an event driven programming design?

That is, how will I know that I cannot run into "a sequence of unfortunate events"?  I want to avoid the events I didn't plan for.

Are there unit tests schemes to test event driven programming?

Observable collections are found at:

http://msdn.microsoft.com/en-us/library/ms668604.aspx

答:
I'd echo some of Glen's answer here. Event-driven programming, taken to a deep level, can be the worst debugging nightmare ever. You also can't effectively unit test against it, since it's almost always temporal in nature with side effects that aren't violating object-level invariants, but broad system-level invariants (the individual objects can be in a valid state, but combined together aren't in the expected state).

A lot of the complexity of large-scale systems in trying to reason about their correctness to me is the combination of side effects and event-driven programming. Side effects are always a tripping point, and event-driven programming tends to make it a mystery about what actually is going to happen when an event is triggered. The two combined, when looking down at millions of lines of code and call stacks which are 45 levels deep, can make the most deadly concoction.

Maintainability in terms of being able to effectively make changes is one aspect, but correctness and reliability is a huge other one. It's hard to get an overall sense of correctness when the control flow is going wildly all over the place with deeply nested function calls, and further if those function calls are not known in advance (involving a dynamic dispatch, as in the case of events). Observers of observers of observers is not a pleasant thing here.

... and this graph is simplified. When you're dealing with really complex systems spanning millions of lines of code that go all out on events in this way, running into that unfortunate series of events doesn't seem like a probability, but an inevitability if there is any possible way your system can break if things are called in an arbitrary order.

I've worked with some developers who thought exception-handling was obfuscating control flow with how throwing would branch potentially way down the call stack. Pshaw, that's just a linear branch unwinding the stack. Try to guess where some arbitrary event triggered will actually lead us (the full comprehensive graph) from a control flow perspective in a very complex system, and that tends to be an absolute ??? until we trace into the whole thing in its entirety.

The only strategy I've found to fight against this is:

Do broad integration testing. Protect yourself. Unit testing is largely useless here, as events are often attached in a site-specific way and it's only through a very unusual combination of events that we run into bugs. It needs to be broad integration testing to cover the possibilities of these unfortunate series of events.

Assert liberally. Assertions in the middle of production code and outside of testing are kind of like a poor man's "on-the-site" testing, but in these kinds of cases which are so hard to test for, running into an assertion failure can be a lifesaver as opposed to just some odd side effect which leads to more odd side effects which lead to more for the person debugging without actually bringing the process to a jarring halt.

Strive for a shallower call stack (not so much to the point of epic functions that are their own debugging nightmare, but there's something to be said for centralized code in one function that processes things in a straight top-to-bottom fashion with possibly some loops here and there). Don't recursively trigger events if you can help it.

Whenever possible, swallow up events and turn it into like a concurrent event-queue, waking up a thread and processed in one central loop. It helps flatten the whole thing and kind of centralize the timing of when events occur. It also fights against "event spam processing" inefficiencies where you might otherwise be tempted to do expensive work redundantly when two or more events could just lead to one update of some data structure or a screen refresh, e.g.

Continued from #4, invert push paradigms to more pull paradigms. There are ways to implement pull paradigms without burning up cycles needlessly polling, as with a concurrent queue which often uses condition variables to wake up a thread when the queue is non-empty.

Favor immutability whenever possible. Side effects to central data structures are difficult to reason about, and ever more so when there is no sanity or predictability to the order in which they happen which is especially true in a complex event-driven system where you might have no idea what actually gets called when a button is clicked until you trace into the entire graph and map the control flow in a diagram.

I haven't tried this, but it might be a fine idea to make it impossible in advance to trigger recursive events. Instead, for example, a recursive attempt to trigger an event might defer the actual signal/notification until the processing of the current event is completely finished. This will not necessarily protect against an unfortunate series of events, but will keep the call stack shallower which makes tracing easier (as well as simplifying the conceptual graph). As Glen said, the more constraints and limitations you impose on your event system upfront, the easier your life will generally become. "Uber-flexible event system" should be a warning sign raising red flags rather than something that we applaud.


问:
Do dynamically typed languages, such as Ruby and JavaScript, do any dynamic type checking?
If we look at the definition of "dynamically-typed programming languages" in Wikipedia, it says:

Programming languages which include dynamic type-checking but not static type-checking are often called "dynamically-typed programming languages".

and

Dynamic type-checking is the process of verifying the type safety of a program at runtime. Implementations of dynamically type-checked languages generally associate each runtime object with a "type tag" (i.e., a reference to a type) containing its type information. This runtime type information (RTTI) can also be used to implement dynamic dispatch, late binding, downcasting, reflection, and similar features.

But the thing is, when using Ruby and JavaScript, I never see the type being "checked".

In a video I watched before, the author said that static typed just means a variable's type is defined / declared and compiled, and cannot change, while dynamic typed means a variable's type can change any time when the program is running, and I see it describing static / dynamic typed quite clearly and simply.

Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message?  That is, when using dynamically typed languages, I don't really see it "checked" as in "Dynamic type-checking".  Does or when does the checking happen?

答:
When we describe a language as type-checked, we mean that the language won't let you perform operations invalid for the type. Neither statically nor dynamically typed languages will let you multiply strings together, call a number in the place of a function, etc. A language without type checking would let you do all of those things without complaint.

Whether you do this by checking all the types at compile time, by checking the types at runtime, or seeing if an object responds to a message is an implementation detail of each language. All of those techniques fall under the rubric of type checking.


问:
Implementing "buy one get one for free" coupon logic for shopping cart
Trying to solve bogo coupon logic with proper design pattern, but having trouble identifying one.

Use case: "Buy iPad get SmartCase for free"

Suppose we have the following objects:

```<code>Product:
 - getPrice

CartItem(Product p, quantity):
 - getPrice

Cart:
 - getItems()
 - addItem(CartItem ci)

Coupon(code):
 - getCode

CouponBuyOneGetOneFree(code) extends Coupon: (not sure about inheritance here)
</code>```

1) What design pattern fits here?

2) What if i needed to set up the same logic without coupon but in product settings itself?

I have implemented Decorator pattern for CartItem when discount is applied to the same CartItem by this example and it works great, but still can not achieve the result of this use case.

Somehow I need to check that Ipad and SmartCase both are in the cart and apply discount to SmartCase only. Also if I add another iPad i should get another SmartCase for free.

答:
Real world process seems suitable here. I would separate collection of Coupons from Cart (CartItems collection) by encapsulating them in Checkout object.

Items in cart have its standard price until coupons changes it. Discounts are given at checkout and so does free items. Checkout process goes like this:

Each CartItem is taken out from cart and becomes CheckoutItem

CheckoutItem has additional property - discount (0 at start)

Each Coupon takes a peak at CheckoutItem collection and based on what's in there:

increases discount of single item,

adds "free" item

adds "meta-item" with negative price (total/subtotal discounts)

Additional items are ignored by subsequent coupons (price > 0 should suffice) to avoid cascade effect

Coupons that changed something at checkout are taken away from user

After iterating all coupons CheckoutItems properties may be presented back to user and create order eventually.

Ps. Checkout might not be right name when coupons show its value up front (before adding item to cart), but process shouldn't change imo.


答:
Javascript:

```<code>>>> 1()
TypeError: 1 is not a function
</code>```

Ruby:

```<code>>>> 1 + ""
String can't be coerced into Fixnum
</code>```

These are both simple cases of dynamic type error. Many languages, including almost all dynamic languages but also, e.g., C# and Java, do "type tagging". That is, the runtimes of these environments must, in effect, attach a representation of a type to every object. This is different than static typing because type tags exist at runtime and in at least the dynamic, imperative languages like Ruby and Javascript one variable may point to different objects with different types.

The runtime must, to implement the semantics of the language, check these type tags all the time. For instance, in performing the + operation on two objects, these languages check the type tags on both objects to decide what to do. If both objects are tagged as numeric, then addition is performed (possibly after some type conversion to a common numeric type). If both objects are tagged as string type-tags, then string concatenation is performed. (What may have tripped you up is that Javascript will perform extensive amounts of runtime-type conversions in normal operation. This makes it seem like it is not checking type-tags, because no type errors are thrown, when in fact type-tags are being checked all over the place to perform these conversions.)

Note that this type-tag checking bears only a vague and mostly misleading resemblance to (static) type checking. Static type checking checks properties of the expression before run time while type-tag checking checks properties of the value the expression expresses at run time. Both Ruby and Javascript perform type-tag checking in their basic runtime environment (e.g. in +, -, function invocation). They also allow the user of the language to perform type-tag introspection. That is, they allow the user to check the type-tag of a value at runtime.

Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message?

I am not familiar with this definition, but it strikes me as misleading. A static type is a token that gets associated according to a set of typing rules with expressions in a language and is used to define which expressions are semantically valid in that language. A "dynamic type" (or type-tag, as I prefer) is a value that gets associated with objects in a language's runtime. In some sense, both are tied to interfaces. In statically typed languages, the type defines what expressions an expression of that type may legally appear in and so to that extent determines an interface for that type. Vaguely similarly, type-tags determine, in part, which operations will end in a runtime "TypeError" before the operation is even attempted.

However, it is misleading to identify the type/type-tag with its interface in most static-dynamic languages. Essentially all static and dynamic languages are largely nomatively and not structurally typed. That is, in a normal statically typed language, if you define a type YourCustomer and I define MyCustomer, expressions of the two types will not be interchangeable. even if the definitions of YourCustomer and MyCustomer are identical up to naming. Similarly, if you define a Javascript object with type-tag YourJSCustomer and I define a Javascript object with type-tag MyJSCustomer, even if these two objects have all the same properties and methods otherwise they will not be interchangeable in the face of type-tag introspection.

It is true that in many dynamically typed languages, type-tag introspection is not always used and so YourJSCustomer and MyJSCustomer will be interchangeable in many environments. This is because these languages allow replacing or supplementing type-tag checking with attribute-checking. So if you call x.foo() in JS, Ruby, Python, &c., it will look for the .foo attribute on the object x. This allows the elimination of some, but typically not all, type-tag checking.

Note that in statically typed languages with structural typing, you can have YourCustomer and MyCustomer interchangeable in most/all contexts. This gives a language feel much closer to a language like Javascript or Ruby. I would suggest looking at TypeScript for this, which adds a type system to Javascript.

Title: Do dynamically typed languages, such as Ruby and JavaScript, do any dynamic type checking?

Body:
If we look at the definition of "dynamically-typed programming languages" in Wikipedia, it says:

Programming languages which include dynamic type-checking but not static type-checking are often called "dynamically-typed programming languages".

and

Dynamic type-checking is the process of verifying the type safety of a program at runtime. Implementations of dynamically type-checked languages generally associate each runtime object with a "type tag" (i.e., a reference to a type) containing its type information. This runtime type information (RTTI) can also be used to implement dynamic dispatch, late binding, downcasting, reflection, and similar features.

But the thing is, when using Ruby and JavaScript, I never see the type being "checked".

In a video I watched before, the author said that static typed just means a variable's type is defined / declared and compiled, and cannot change, while dynamic typed means a variable's type can change any time when the program is running, and I see it describing static / dynamic typed quite clearly and simply.

Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message?  That is, when using dynamically typed languages, I don't really see it "checked" as in "Dynamic type-checking".  Does or when does the checking happen?

Body:
Javascript:

>>> 1()
TypeError: 1 is not a function

Ruby:

>>> 1 + ""
String can't be coerced into Fixnum

These are both simple cases of dynamic type error. Many languages, including almost all dynamic languages but also, e.g., C# and Java, do "type tagging". That is, the runtimes of these environments must, in effect, attach a representation of a type to every object. This is different than static typing because type tags exist at runtime and in at least the dynamic, imperative languages like Ruby and Javascript one variable may point to different objects with different types.

The runtime must, to implement the semantics of the language, check these type tags all the time. For instance, in performing the + operation on two objects, these languages check the type tags on both objects to decide what to do. If both objects are tagged as numeric, then addition is performed (possibly after some type conversion to a common numeric type). If both objects are tagged as string type-tags, then string concatenation is performed. (What may have tripped you up is that Javascript will perform extensive amounts of runtime-type conversions in normal operation. This makes it seem like it is not checking type-tags, because no type errors are thrown, when in fact type-tags are being checked all over the place to perform these conversions.)

Note that this type-tag checking bears only a vague and mostly misleading resemblance to (static) type checking. Static type checking checks properties of the expression before run time while type-tag checking checks properties of the value the expression expresses at run time. Both Ruby and Javascript perform type-tag checking in their basic runtime environment (e.g. in +, -, function invocation). They also allow the user of the language to perform type-tag introspection. That is, they allow the user to check the type-tag of a value at runtime.

Actually, according to GoF, a type is simply a set of interface, so how can you "check" the type, other than whether it responds to a particular message?

I am not familiar with this definition, but it strikes me as misleading. A static type is a token that gets associated according to a set of typing rules with expressions in a language and is used to define which expressions are semantically valid in that language. A "dynamic type" (or type-tag, as I prefer) is a value that gets associated with objects in a language's runtime. In some sense, both are tied to interfaces. In statically typed languages, the type defines what expressions an expression of that type may legally appear in and so to that extent determines an interface for that type. Vaguely similarly, type-tags determine, in part, which operations will end in a runtime "TypeError" before the operation is even attempted.

However, it is misleading to identify the type/type-tag with its interface in most static-dynamic languages. Essentially all static and dynamic languages are largely nomatively and not structurally typed. That is, in a normal statically typed language, if you define a type YourCustomer and I define MyCustomer, expressions of the two types will not be interchangeable. even if the definitions of YourCustomer and MyCustomer are identical up to naming. Similarly, if you define a Javascript object with type-tag YourJSCustomer and I define a Javascript object with type-tag MyJSCustomer, even if these two objects have all the same properties and methods otherwise they will not be interchangeable in the face of type-tag introspection.

It is true that in many dynamically typed languages, type-tag introspection is not always used and so YourJSCustomer and MyJSCustomer will be interchangeable in many environments. This is because these languages allow replacing or supplementing type-tag checking with attribute-checking. So if you call x.foo() in JS, Ruby, Python, &c., it will look for the .foo attribute on the object x. This allows the elimination of some, but typically not all, type-tag checking.

Note that in statically typed languages with structural typing, you can have YourCustomer and MyCustomer interchangeable in most/all contexts. This gives a language feel much closer to a language like Javascript or Ruby. I would suggest looking at TypeScript for this, which adds a type system to Javascript.


问:
Accessing information between GUIs in Java
I'm fairly new to Java and GUIs and am trying to work on a side project. I'm finding that as I continue to make more and more GUIs within eachother, I am continuously needing to access information that originated in the first GUI, from within deeper GUIs.

For example, I have a variable in the first GUI, after a user clicks on four or five sequential buttons (thus 4 or 5 GUIs later), I need to access said information.

So far I've just been passing this information into the initialization of the GUIs via their constructors, thus accessing it from there. Is this the "proper" way of accessing said information? Or is there a convention/more efficient way of doing so?

Example:

Within the first (main) GUI, I have a variable holding a username. After the user clicks on "Login" - then "Account Settings" then "Profile" - from within the "Profile" GUI, I need to access the variable "userName" originating in the main GUI. Currently I just pass this information into the constructors leading to Profile - is there a better way to do this? Perhaps a way to centralize all this information?

答: No, it's bad idea to pass data from GUI to GUI via constructors, what you could do is to create a simple singleton service to hold your data which can be injected to the UI via the constructor. </p>


问:
Conquering Complexity: Valuable techniques
Software development techniques exist to solve problems. I think a key problem we face is conquering complexity. Also, software developers must often classify and understand complex systems, separating accidental complexity from essential complexity.   I believe that sufficiently useful definitions of these terms all exist on Wikipedia.

My question is: What techniques are most valuable in conquering complexity, as a professional software developer, and/or software architect?

Answer examplar; a blog post on conquering complexity that seems to be coming at things from a java/c++/OOP centric perspective.

答:
Make your system flat instead of deep: big objects that don't talk to each much at all, not a boatload of teeny ones talking to each other. One type of data can often be modified in one central place in a loopy fashion, like PhysicsSystem.

You don't need to disperse that logic across 50 different classes that have to talk to each other and mutate their own little localized state. Doing so will lead to each one being individually simpler, but to reason about what they do physics-wise, will be, as a whole, far more complex due to the spiderweb of interactions that introduces. Just stop and think about breaking that physics system down into 50 different classes and abstract interfaces, however individually simple. Think about what that really does to your ability to comprehend what the physics engine will do, and realize how retarded we can be with OOP, making things exponentially more complicated as a whole in an effort to make each individual one simple.

Look at how game engines do it. They have the right idea.

The notion of a Car entity contributes barely any complexity to the system, as it is merely a collection of components and contributes no functionality to the system. And the components barely contribute any complexity to the system, since they are just data. The system breaks down into a straightforward flat pipeline of heavyweight, largely independent systems containing the functionality, not a deep spiderweb of interactions between abstract interfaces representing the most granular ideas far divorced from the business requirements. Not only will it substantially reduce the code required for the software, it will also make it easy to break down its design into a handful of systems you need while allowing you to talk to managers and customers about the system organization (which is literally just the organization of these systems) in a way that they can actually comprehend to a far greater degree, like PhysicsSystem, RenderSystem, etc.

And it's extensible and maintainable AF, allowing you to tackle whole new unanticipated design ideas of a kind that would break the most carefully designed abstractions, while still only requiring you to change one place in the code without cascading changes.


问:
Is possible to write too many asserts?
I am a big fan of writing assert checks in C++ code as a way to catch cases during development that cannot possibly happen but do happen because of logic bugs in my program. This is a good practice in general.

However, I've noticed that some functions I write (which are part of a complex class) have 5+ asserts which feels like it could potentially be a bad programming practice, in terms of readability and maintainability. I think it's still great, as each one requires me to think about pre- and post-conditions of functions and they really do help catch bugs. However, I just wanted to put this out there to ask if there is a better paradigms for catching logic errors in cases when a large number of checks is necessary.

Emacs comment: Since Emacs is my IDE of choice, I have it slightly gray out the assert statements which helps reduce the feeling of clutter that they can provide. Here's what I add to my .emacs file:

```<code>; gray out the "assert(...)" wrapper
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<\\(assert\(.*\);\\)" 1 '(:foreground "#444444") t)))))

; gray out the stuff inside parenthesis with a slightly lighter color
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<assert\\(\(.*\);\\)" 1 '(:foreground "#666666") t)))))
</code>```

答:
Is possible to write too many asserts?

Well, of course it is. [Imagine obnoxious example here.] However, applying the guidelines detailed in the following, you shouldn't have troubles pushing that limit in practice. I'm a big fan of assertions, too, and I use them according to these principles. Much of this advice is not special to assertions but only general good engineering practice applied to them.

Keep the run-time and binary footprint overhead in mind

Assertions are great, but if they make your program unacceptably slow, it will be either very annoying or you will turn them off sooner or later.

I like to gauge the cost of an assertion relative to the cost of the function it is contained in.  Consider the following two examples.

```<code>// Precondition:  queue is not empty
// Invariant:     queue is sorted
template <typename T>
const T&
sorted_queue<T>::max() const noexcept
{
  assert(!this->data_.empty());
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  return this->data_.back();
}
</code>```

The function itself is an O(1) operation but the assertions account for O(n) overhead. I don't think that you would like such checks to be active unless in very special circumstances.

Here is another function with similar assertions.

```<code>// Requirement:   op : T -> T is monotonic [ie x <= y implies op(x) <= op(y)]
// Invariant:     queue is sorted
// Postcondition: each item x in the queue is replaced by op(x)
template <typename T>
template <typename FuncT>
void
sorted_queue<T>::apply_monotonic_function(FuncT&& op)
{
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  std::transform(std::cbegin(this->data_), std::cend(this->data_),
                 std::begin(this->data_), std::forward<FuncT>(op));
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
}
</code>```

The function itself is an O(n) operation so it hurts much less to add an additional O(n) overhead for the assertion. Slowing down a function by a small (in this case, probably less than 3) constant factor is something we can usually afford in a debug build but maybe not in a release build.

Now consider this example.

```<code>// Precondition:  queue is not empty
// Invariant:     queue is sorted
// Postcondition: last element is removed from queue
template <typename T>
void
sorted_queue<T>::pop_back() noexcept
{
  assert(!this->data_.empty());
  return this->data_.pop_back();
}
</code>```

While many people will probably be much more comfortable with this O(1) assertion than with the two O(n) assertions in the previous example, they are morally equivalent in my view. Each adds overhead on the order of the complexity of the function itself.

Finally, there are the “really cheap” assertions that are dominated by the complexity of the function they're contained in.

```<code>// Requirement:   cmp : T x T -> bool is a strict weak ordering
// Precondition:  queue is not empty
// Postcondition: if x is returned, then there is no y in the queue
//                such that cmp(x, y)
template <typename T>
template <typename CmpT>
const T&
sorted_queue<T>::max(CmpT&& cmp) const
{
  assert(!this->data_.empty());
  const auto pos = std::max_element(std::cbegin(this->data_),
                                    std::cend(this->data_),
                                    std::forward<CmpT>(cmp));
  assert(pos != std::cend(this->data_));
  return *pos;
}
</code>```

Here, we have two O(1) assertions in an O(n) function. It probably won't be a problem to keep this overhead even in release builds.

Do keep in mind, however, that asymptotic complexities are not always giving an adequate estimate because in practice, we are always dealing with input sizes bounded by some finite constant and constant factors hidden by “Big-O” might very well be not negligible.

So now we have identified different scenarios, what can we do about them? An (probably too) easy approach would be to follow a rule such as “Don't use assertions that dominate the function they are contained in.” While it might work for some projects, others might need a more differentiated approach. This could be done by using different assertion macros for the different cases.

```<code>#define MY_ASSERT_IMPL(COST, CONDITION)                                       \
  (                                                                           \
    ( ((COST) <= (MY_ASSERT_COST_LIMIT)) && !(CONDITION) )                    \
      ? ::my::assertion_failed(__FILE__, __LINE__, __FUNCTION__, # CONDITION) \
      : (void) 0                                                              \
  )

#define MY_ASSERT_LOW(CONDITION)                                              \
  MY_ASSERT_IMPL(MY_ASSERT_COST_LOW, CONDITION)

#define MY_ASSERT_MEDIUM(CONDITION)                                           \
  MY_ASSERT_IMPL(MY_ASSERT_COST_MEDIUM, CONDITION)

#define MY_ASSERT_HIGH(CONDITION)                                             \
  MY_ASSERT_IMPL(MY_ASSERT_COST_HIGH, CONDITION)

#define MY_ASSERT_COST_NONE    0
#define MY_ASSERT_COST_LOW     1
#define MY_ASSERT_COST_MEDIUM  2
#define MY_ASSERT_COST_HIGH    3
#define MY_ASSERT_COST_ALL    10

#ifndef MY_ASSERT_COST_LIMIT
#  define MY_ASSERT_COST_LIMIT MY_ASSERT_COST_MEDIUM
#endif

namespace my
{

  [[noreturn]] extern void
  assertion_failed(const char * filename, int line, const char * function,
                   const char * message) noexcept;

}
</code>```

You can now use the three macros MY_ASSERT_LOW, MY_ASSERT_MEDIUM and MY_ASSERT_HIGH instead of the standard library's “one size fits all” assert macro for assertions that are dominated by, neither dominated by nor dominating and dominating the complexity of their containing function respectively. When you build the software, you can pre-define the pre-processor symbol MY_ASSERT_COST_LIMIT to select what kind of assertions should make it into the executable. The constants MY_ASSERT_COST_NONE and MY_ASSERT_COST_ALL don't correspond to any assert macros and are meant to be used as values for MY_ASSERT_COST_LIMIT in order to turn all assertions off or on respectively.

We're relying on the assumption here that a good compiler will not generate any code for

```<code>if (false_constant_expression && run_time_expression) { /* ... */ }
</code>```

and transform

```<code>if (true_constant_expression && run_time_expression) { /* ... */ }
</code>```

into

```<code>if (run_time_expression) { /* ... */ }
</code>```

which I believe is a safe assumption nowadays.

If you're about to tweak the above code, consider compiler-specific annotations like __attribute__ ((cold)) on my::assertion_failed or __builtin_expect(…, false) on !(CONDITION) to reduce the overhead of passed assertions. In release builds, you may also consider replacing the function call to my::assertion_failed with something like __builtin_trap to reduce the foot-print at the inconvenience of losing a diagnostic message.

These kinds of optimizations are really only relevant in extremely cheap assertions (like comparing two integers that are already given as arguments) in a function that itself is very compact, not considering the additional size of the binary accumulated by incorporating all the message strings.

Compare how this code

```<code>int
positive_difference_1st(const int a, const int b) noexcept
{
  if (!(a > b))
    my::assertion_failed(__FILE__, __LINE__, __FUNCTION__, "!(a > b)");
  return a - b;
}
</code>```

is compiled into the following assembly

_ZN4test23positive_difference_1stEii:
.LFB0:
        .cfi_startproc
        cmpl    %esi, %edi
        jle     .L5
        movl    %edi, %eax
        subl    %esi, %eax
        ret
.L5:
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        movl    $.LC0, %ecx
        movl    $_ZZN4test23positive_difference_1stEiiE12__FUNCTION__, %edx
        movl    $50, %esi
        movl    $.LC1, %edi
        call    _ZN2my16assertion_failedEPKciS1_S1_
        .cfi_endproc
.LFE0:
```

<p>while the following code</p>

```int
positive_difference_2nd(const int a, const int b) noexcept
{
  if (__builtin_expect(!(a > b), false))
    __builtin_trap();
  return a - b;
}
```

<p>gives this assembly</p>

<pre class="lang-none prettyprint-override"><code>_ZN4test23positive_difference_2ndEii:
.LFB1:
        .cfi_startproc
        cmpl    %esi, %edi
        jle     .L8
        movl    %edi, %eax
        subl    %esi, %eax
        ret
        .p2align 4,,7
        .p2align 3
.L8:
        ud2
        .cfi_endproc
.LFE1:
</code>```

which I feel much more comfortable with. (Examples were tested with GCC 5.3.0 using the -std=c++14, -O3 and -march=native flags on 4.3.3-2-ARCH x86_64 GNU/Linux. Not shown in the above snippets are the declarations of test::positive_difference_1st and test::positive_difference_2nd which I added the __attribute__ ((hot)) to. my::assertion_failed was declared with __attribute__ ((cold)).)

Assert preconditions in the function that depends on them

Suppose you have the following function with the specified contract.

```<code>// Requirement:   op : T -> T is monotonic [ie x <= y implies op(x) <= op(y)]
// Invariant:     queue is sorted
// Postcondition: each item x in the queue is replaced by op(x)
template <typename T>
template <typename FuncT>
void
sorted_queue<T>::apply_monotonic_function(FuncT&& op)
{
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  std::transform(std::cbegin(this->data_), std::cend(this->data_),
                 std::begin(this->data_), std::forward<FuncT>(op));
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
}
</code>```0

Instead of writing

```<code>// Requirement:   op : T -> T is monotonic [ie x <= y implies op(x) <= op(y)]
// Invariant:     queue is sorted
// Postcondition: each item x in the queue is replaced by op(x)
template <typename T>
template <typename FuncT>
void
sorted_queue<T>::apply_monotonic_function(FuncT&& op)
{
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  std::transform(std::cbegin(this->data_), std::cend(this->data_),
                 std::begin(this->data_), std::forward<FuncT>(op));
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
}
</code>```1

at each call-site, put that logic once into the definition of count_letters

```<code>// Requirement:   op : T -> T is monotonic [ie x <= y implies op(x) <= op(y)]
// Invariant:     queue is sorted
// Postcondition: each item x in the queue is replaced by op(x)
template <typename T>
template <typename FuncT>
void
sorted_queue<T>::apply_monotonic_function(FuncT&& op)
{
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  std::transform(std::cbegin(this->data_), std::cend(this->data_),
                 std::begin(this->data_), std::forward<FuncT>(op));
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
}
</code>```2

and call it without further ado.

```<code>const auto frequency = count_letters(text, letter);
</code>```

This has the following advantages.

You only need to write the assertion code once. Since the very purpose of functions is that they be called – often more than once – this should reduce the overall number of assert statements in your code.

It keeps the logic that checks the preconditions close to the logic that depends on them. I think this is the most important aspect. If your clients misuse your interface, they cannot be assumed to apply the assertions correctly either so it is better the function tells them.

The obvious disadvantage is that you won't get the source location of the call-site into the diagnostic message. I believe that this is a minor issue. A good debugger should be able to let you trace back the origin of the contract violation conveniently.

The same thinking applies to “special” functions like overloaded operators. When I'm writing iterators, I usually – if the nature of the iterator allows it – give them a member function

```<code>bool
good() const noexcept;
</code>```

that allows to ask whether it is safe to dereference the iterator. (Of course, in practice, it is almost always only possible to guarantee that it won't be safe to dereference the iterator. But I believe you can still catch a lot of bugs with such a function.) Instead of littering all my code that uses the iterator with assert(iter.good()) statements, I'd rather put a single assert(this->good()) as the first line of the operator* in the iterator's implementation.

If you're using the standard library, instead of asserting manually on its preconditions in your source code, turn on their checks in debug builds. They can do even more sophisticated checks like testing whether the container an iterator refers to still exists. (See the documentation for libstdc++ and libc++ (work in progress) for more information.)

Factor common conditions out

Suppose you're writing a linear algebra package. Many functions will have complicated preconditions and violating them will often cause wrong results that are not immediately recognizable as such. It would be very good if these functions asserted their preconditions. If you define a bunch of predicates that tell you certain properties about a structure, those assertions become much more readable.

```<code>template <typename MatrixT>
auto
cholesky_decompose(MatrixT&& m)
{
  assert(is_square(m) && is_symmetric(m));
  // TODO: Somehow decompose that thing...
}
</code>```

It will also give more useful error messages.

cholesky.hxx:357: cholesky_decompose: assertion failed: is_symmetric(m)
```

<p>helps a lot more than, say</p>

<pre class="lang-none prettyprint-override"><code>detail/basic_ops.hxx:1289: fast_compare: assertion failed: m(i, j) == m(j, i)
</code>```

where you'd first have to go look at the source code in the context to figure out what was actually tested.

If you have a class with non-trivial invariants, it is probably a good idea to assert on them from time to time when you have messed with the internal state and want to ensure that you're leaving the object in a valid state on return.

For this purpose, I found it useful to define a private member function that I conventionally call class_invaraiants_hold_. Suppose you were re-implementing std::vector (Because we all know it ain't good enough.), it might have a function like this.

```<code>template <typename T>
bool
vector<T>::class_invariants_hold_() const noexcept
{
  if (this->size_ > this->capacity_)
    return false;
  if ((this->size_ > 0) && (this->data_ == nullptr))
    return false;
  if ((this->capacity_ == 0) != (this->data_ == nullptr))
    return false;
  return true;
}
</code>```

Notice a few things about this.

The predicate function itself is const and noexcept, in accordance with the guideline that assertions shall not have side effects. If it makes sense, also declare it constexpr.

The predicate doesn't assert anything itself. It is meant to be called inside assertions, such as assert(this->class_invariants_hold_()). This way, if assertions are compiled-out, we can be sure that no run-time overhead is incurred.

The control flow inside the function is broken apart into multiple if statements with early returns rather than a large expression. This makes it easy to step through the function in a debugger and find out what part of the invariant was broken if the assertion fires.

Don't assert on silly things

Some things just don't make sense to assert on.

```<code>auto numbers = std::vector<int> {};
numbers.push_back(14);
numbers.push_back(92);
assert(numbers.size() == 2);  // silly
assert(!numbers.empty());     // silly and redundant
</code>```

These assertions don't make the code even a tiny bit more readable or easier to reason about. Every C++ programmer should be confident enough how std::vector works to be certain that the above code is correct simply by looking at it. I'm not saying that you should never assert on a container's size. If you have added or removed elements using some non-trivial control flow, such an assertion can be useful. But if it merely repeats what was written in non-assertion code just above, there is no value gained.

Also don't assert that library functions work correctly.

```<code>auto w = widget {};
w.enable_quantum_mode();
assert(w.quantum_mode_enabled());  // probably silly
</code>```

If you trust the library that little, better consider using another library instead.

On the other hand, if the documentation of the library is not 100 % clear and you gain confidence about its contracts by reading the source code, it makes a lot of sense to assert on that “inferred contract”. If it is broken in a future version of the library, you'll notice quickly.

```<code>auto w = widget {};
// After reading the source code, I have concluded that quantum mode is
// always off by default but this isn't documented anywhere.
assert(!w.quantum_mode_enabled());
</code>```

This is better than the following solution which will not tell you whether your assumptions were correct.

```<code>// Precondition:  queue is not empty
// Invariant:     queue is sorted
// Postcondition: last element is removed from queue
template <typename T>
void
sorted_queue<T>::pop_back() noexcept
{
  assert(!this->data_.empty());
  return this->data_.pop_back();
}
</code>```0

Don't abuse assertions to implement program logic

Assertions should only ever be used to uncover bugs that are worthy of immediately killing your application. They should not be used to verify any other condition even if the appropriate reaction to that condition would also be to quit immediately.

Therefore, write this…

```<code>// Precondition:  queue is not empty
// Invariant:     queue is sorted
// Postcondition: last element is removed from queue
template <typename T>
void
sorted_queue<T>::pop_back() noexcept
{
  assert(!this->data_.empty());
  return this->data_.pop_back();
}
</code>```1

…instead of that.

```<code>// Precondition:  queue is not empty
// Invariant:     queue is sorted
// Postcondition: last element is removed from queue
template <typename T>
void
sorted_queue<T>::pop_back() noexcept
{
  assert(!this->data_.empty());
  return this->data_.pop_back();
}
</code>```2

Also never use assertions to validate untrusted input or check that std::malloc did not return you the nullptr. Even if you know that you'll never turn assertions off, even in release builds, an assertion communicates to the reader that it checks something that is always true given that the program is bug-free and has no visible side-effects. If this is not the kind of message you want to communicate, use an alternative error handling mechanism such as throwing an exception. If you find it convenient to have a macro wrapper for your non-assertion checks, go ahead writing one. Just don't call it “assert”, “assume”, “require”, “ensure” or something like that. Its internal logic could be the same as for assert, except that it is never compiled out, of course.

More information

I found John Lakos' talk Defensive Programming Done Right, given at CppCon'14 (1st part, 2nd part) very enlightening. He takes the idea of customizing what assertions are enabled and how to react on failed exceptions even further than I did in this answer.

Title: Is possible to write too many asserts?

Body:
Is possible to write too many asserts?

Well, of course it is. [Imagine obnoxious example here.] However, applying the guidelines detailed in the following, you shouldn't have troubles pushing that limit in practice. I'm a big fan of assertions, too, and I use them according to these principles. Much of this advice is not special to assertions but only general good engineering practice applied to them.

Keep the run-time and binary footprint overhead in mind

Assertions are great, but if they make your program unacceptably slow, it will be either very annoying or you will turn them off sooner or later.

I like to gauge the cost of an assertion relative to the cost of the function it is contained in.  Consider the following two examples.

// Precondition:  queue is not empty
// Invariant:     queue is sorted
template <typename T>
const T&
sorted_queue<T>::max() const noexcept
{
  assert(!this->data_.empty());
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  return this->data_.back();
}

The function itself is an O(1) operation but the assertions account for O(n) overhead. I don't think that you would like such checks to be active unless in very special circumstances.

Here is another function with similar assertions.

// Requirement:   op : T -> T is monotonic [ie x <= y implies op(x) <= op(y)]
// Invariant:     queue is sorted
// Postcondition: each item x in the queue is replaced by op(x)
template <typename T>
template <typename FuncT>
void
sorted_queue<T>::apply_monotonic_function(FuncT&& op)
{
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
  std::transform(std::cbegin(this->data_), std::cend(this->data_),
                 std::begin(this->data_), std::forward<FuncT>(op));
  assert(std::is_sorted(std::cbegin(this->data_), std::cend(this->data_)));
}

The function itself is an O(n) operation so it hurts much less to add an additional O(n) overhead for the assertion. Slowing down a function by a small (in this case, probably less than 3) constant factor is something we can usually afford in a debug build but maybe not in a release build.

Now consider this example.

// Precondition:  queue is not empty
// Invariant:     queue is sorted
// Postcondition: last element is removed from queue
template <typename T>
void
sorted_queue<T>::pop_back() noexcept
{
  assert(!this->data_.empty());
  return this->data_.pop_back();
}

While many people will probably be much more comfortable with this O(1) assertion than with the two O(n) assertions in the previous example, they are morally equivalent in my view. Each adds overhead on the order of the complexity of the function itself.

Finally, there are the “really cheap” assertions that are dominated by the complexity of the function they're contained in.

// Requirement:   cmp : T x T -> bool is a strict weak ordering
// Precondition:  queue is not empty
// Postcondition: if x is returned, then there is no y in the queue
//                such that cmp(x, y)
template <typename T>
template <typename CmpT>
const T&
sorted_queue<T>::max(CmpT&& cmp) const
{
  assert(!this->data_.empty());
  const auto pos = std::max_element(std::cbegin(this->data_),
                                    std::cend(this->data_),
                                    std::forward<CmpT>(cmp));
  assert(pos != std::cend(this->data_));
  return *pos;
}

Here, we have two O(1) assertions in an O(n) function. It probably won't be a problem to keep this overhead even in release builds.

Do keep in mind, however, that asymptotic complexities are not always giving an adequate estimate because in practice, we are always dealing with input sizes bounded by some finite constant and constant factors hidden by “Big-O” might very well be not negligible.

So now we have identified different scenarios, what can we do about them? An (probably too) easy approach would be to follow a rule such as “Don't use assertions that dominate the function they are contained in.” While it might work for some projects, others might need a more differentiated approach. This could be done by using different assertion macros for the different cases.

#define MY_ASSERT_IMPL(COST, CONDITION)                                       \
  (                                                                           \
    ( ((COST) <= (MY_ASSERT_COST_LIMIT)) && !(CONDITION) )                    \
      ? ::my::assertion_failed(__FILE__, __LINE__, __FUNCTION__, # CONDITION) \
      : (void) 0                                                              \
  )

#define MY_ASSERT_LOW(CONDITION)                                              \
  MY_ASSERT_IMPL(MY_ASSERT_COST_LOW, CONDITION)

#define MY_ASSERT_MEDIUM(CONDITION)                                           \
  MY_ASSERT_IMPL(MY_ASSERT_COST_MEDIUM, CONDITION)

#define MY_ASSERT_HIGH(CONDITION)                                             \
  MY_ASSERT_IMPL(MY_ASSERT_COST_HIGH, CONDITION)

#define MY_ASSERT_COST_NONE    0
#define MY_ASSERT_COST_LOW     1
#define MY_ASSERT_COST_MEDIUM  2
#define MY_ASSERT_COST_HIGH    3
#define MY_ASSERT_COST_ALL    10

#ifndef MY_ASSERT_COST_LIMIT
#  define MY_ASSERT_COST_LIMIT MY_ASSERT_COST_MEDIUM
#endif

namespace my
{

  [[noreturn]] extern void
  assertion_failed(const char * filename, int line, const char * function,
                   const char * message) noexcept;

}

You can now use the three macros MY_ASSERT_LOW, MY_ASSERT_MEDIUM and MY_ASSERT_HIGH instead of the standard library's “one size fits all” assert macro for assertions that are dominated by, neither dominated by nor dominating and dominating the complexity of their containing function respectively. When you build the software, you can pre-define the pre-processor symbol MY_ASSERT_COST_LIMIT to select what kind of assertions should make it into the executable. The constants MY_ASSERT_COST_NONE and MY_ASSERT_COST_ALL don't correspond to any assert macros and are meant to be used as values for MY_ASSERT_COST_LIMIT in order to turn all assertions off or on respectively.

We're relying on the assumption here that a good compiler will not generate any code for

if (false_constant_expression && run_time_expression) { /* ... */ }

and transform

if (true_constant_expression && run_time_expression) { /* ... */ }

into

if (run_time_expression) { /* ... */ }

which I believe is a safe assumption nowadays.

If you're about to tweak the above code, consider compiler-specific annotations like __attribute__ ((cold)) on my::assertion_failed or __builtin_expect(…, false) on !(CONDITION) to reduce the overhead of passed assertions. In release builds, you may also consider replacing the function call to my::assertion_failed with something like __builtin_trap to reduce the foot-print at the inconvenience of losing a diagnostic message.

These kinds of optimizations are really only relevant in extremely cheap assertions (like comparing two integers that are already given as arguments) in a function that itself is very compact, not considering the additional size of the binary accumulated by incorporating all the message strings.

Compare how this code

int
positive_difference_1st(const int a, const int b) noexcept
{
  if (!(a > b))
    my::assertion_failed(__FILE__, __LINE__, __FUNCTION__, "!(a > b)");
  return a - b;
}

is compiled into the following assembly

_ZN4test23positive_difference_1stEii:
.LFB0:
        .cfi_startproc
        cmpl    %esi, %edi
        jle     .L5
        movl    %edi, %eax
        subl    %esi, %eax
        ret
.L5:
        subq    $8, %rsp
        .cfi_def_cfa_offset 16
        movl    $.LC0, %ecx
        movl    $_ZZN4test23positive_difference_1stEiiE12__FUNCTION__, %edx
        movl    $50, %esi
        movl    $.LC1, %edi
        call    _ZN2my16assertion_failedEPKciS1_S1_
        .cfi_endproc
.LFE0:

while the following code

int
positive_difference_2nd(const int a, const int b) noexcept
{
  if (__builtin_expect(!(a > b), false))
    __builtin_trap();
  return a - b;
}

gives this assembly

_ZN4test23positive_difference_2ndEii:
.LFB1:
        .cfi_startproc
        cmpl    %esi, %edi
        jle     .L8
        movl    %edi, %eax
        subl    %esi, %eax
        ret
        .p2align 4,,7
        .p2align 3
.L8:
        ud2
        .cfi_endproc
.LFE1:

which I feel much more comfortable with. (Examples were tested with GCC 5.3.0 using the -std=c++14, -O3 and -march=native flags on 4.3.3-2-ARCH x86_64 GNU/Linux. Not shown in the above snippets are the declarations of test::positive_difference_1st and test::positive_difference_2nd which I added the __attribute__ ((hot)) to. my::assertion_failed was declared with __attribute__ ((cold)).)

Assert preconditions in the function that depends on them

Suppose you have the following function with the specified contract.

/**
 * @brief
 *         Counts the frequency of a letter in a string.
 *
 * The frequency count is case-insensitive.
 *
 * If `text` does not point to a NUL terminated character array or `letter`
 * is not in the character range `[A-Za-z]`, the behavior is undefined.
 *
 * @param text
 *         text to count the letters in
 *
 * @param letter
 *         letter to count
 *
 * @returns
 *         occurences of `letter` in `text`
 *
 */
std::size_t
count_letters(const char * text, int letter) noexcept;

Instead of writing

assert(text != nullptr);
assert((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'));
const auto frequency = count_letters(text, letter);

at each call-site, put that logic once into the definition of count_letters

std::size_t
count_letters(const char *const text, const int letter) noexcept
{
  assert(text != nullptr);
  assert((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z'));
  auto frequency = std::size_t {};
  // TODO: Figure this out...
  return frequency;
}

and call it without further ado.

const auto frequency = count_letters(text, letter);

This has the following advantages.

You only need to write the assertion code once. Since the very purpose of functions is that they be called – often more than once – this should reduce the overall number of assert statements in your code.

It keeps the logic that checks the preconditions close to the logic that depends on them. I think this is the most important aspect. If your clients misuse your interface, they cannot be assumed to apply the assertions correctly either so it is better the function tells them.

The obvious disadvantage is that you won't get the source location of the call-site into the diagnostic message. I believe that this is a minor issue. A good debugger should be able to let you trace back the origin of the contract violation conveniently.

The same thinking applies to “special” functions like overloaded operators. When I'm writing iterators, I usually – if the nature of the iterator allows it – give them a member function

bool
good() const noexcept;

that allows to ask whether it is safe to dereference the iterator. (Of course, in practice, it is almost always only possible to guarantee that it won't be safe to dereference the iterator. But I believe you can still catch a lot of bugs with such a function.) Instead of littering all my code that uses the iterator with assert(iter.good()) statements, I'd rather put a single assert(this->good()) as the first line of the operator* in the iterator's implementation.

If you're using the standard library, instead of asserting manually on its preconditions in your source code, turn on their checks in debug builds. They can do even more sophisticated checks like testing whether the container an iterator refers to still exists. (See the documentation for libstdc++ and libc++ (work in progress) for more information.)

Factor common conditions out

Suppose you're writing a linear algebra package. Many functions will have complicated preconditions and violating them will often cause wrong results that are not immediately recognizable as such. It would be very good if these functions asserted their preconditions. If you define a bunch of predicates that tell you certain properties about a structure, those assertions become much more readable.

template <typename MatrixT>
auto
cholesky_decompose(MatrixT&& m)
{
  assert(is_square(m) && is_symmetric(m));
  // TODO: Somehow decompose that thing...
}

It will also give more useful error messages.

cholesky.hxx:357: cholesky_decompose: assertion failed: is_symmetric(m)

helps a lot more than, say

detail/basic_ops.hxx:1289: fast_compare: assertion failed: m(i, j) == m(j, i)

where you'd first have to go look at the source code in the context to figure out what was actually tested.

If you have a class with non-trivial invariants, it is probably a good idea to assert on them from time to time when you have messed with the internal state and want to ensure that you're leaving the object in a valid state on return.

For this purpose, I found it useful to define a private member function that I conventionally call class_invaraiants_hold_. Suppose you were re-implementing std::vector (Because we all know it ain't good enough.), it might have a function like this.

template <typename T>
bool
vector<T>::class_invariants_hold_() const noexcept
{
  if (this->size_ > this->capacity_)
    return false;
  if ((this->size_ > 0) && (this->data_ == nullptr))
    return false;
  if ((this->capacity_ == 0) != (this->data_ == nullptr))
    return false;
  return true;
}

Notice a few things about this.

The predicate function itself is const and noexcept, in accordance with the guideline that assertions shall not have side effects. If it makes sense, also declare it constexpr.

The predicate doesn't assert anything itself. It is meant to be called inside assertions, such as assert(this->class_invariants_hold_()). This way, if assertions are compiled-out, we can be sure that no run-time overhead is incurred.

The control flow inside the function is broken apart into multiple if statements with early returns rather than a large expression. This makes it easy to step through the function in a debugger and find out what part of the invariant was broken if the assertion fires.

Don't assert on silly things

Some things just don't make sense to assert on.

auto numbers = std::vector<int> {};
numbers.push_back(14);
numbers.push_back(92);
assert(numbers.size() == 2);  // silly
assert(!numbers.empty());     // silly and redundant

These assertions don't make the code even a tiny bit more readable or easier to reason about. Every C++ programmer should be confident enough how std::vector works to be certain that the above code is correct simply by looking at it. I'm not saying that you should never assert on a container's size. If you have added or removed elements using some non-trivial control flow, such an assertion can be useful. But if it merely repeats what was written in non-assertion code just above, there is no value gained.

Also don't assert that library functions work correctly.

auto w = widget {};
w.enable_quantum_mode();
assert(w.quantum_mode_enabled());  // probably silly

If you trust the library that little, better consider using another library instead.

On the other hand, if the documentation of the library is not 100 % clear and you gain confidence about its contracts by reading the source code, it makes a lot of sense to assert on that “inferred contract”. If it is broken in a future version of the library, you'll notice quickly.

auto w = widget {};
// After reading the source code, I have concluded that quantum mode is
// always off by default but this isn't documented anywhere.
assert(!w.quantum_mode_enabled());

This is better than the following solution which will not tell you whether your assumptions were correct.

auto w = widget {};
if (w.quantum_mode_enabled())
  {
    // I don't think that quantum mode is ever enabled by default but
    // I'm not sure.
    w.disable_quantum_mode();
  }

Don't abuse assertions to implement program logic

Assertions should only ever be used to uncover bugs that are worthy of immediately killing your application. They should not be used to verify any other condition even if the appropriate reaction to that condition would also be to quit immediately.

Therefore, write this…

if (!server_reachable())
  {
    log_message("server not reachable");
    shutdown();
  }

…instead of that.

assert(server_reachable());

Also never use assertions to validate untrusted input or check that std::malloc did not return you the nullptr. Even if you know that you'll never turn assertions off, even in release builds, an assertion communicates to the reader that it checks something that is always true given that the program is bug-free and has no visible side-effects. If this is not the kind of message you want to communicate, use an alternative error handling mechanism such as throwing an exception. If you find it convenient to have a macro wrapper for your non-assertion checks, go ahead writing one. Just don't call it “assert”, “assume”, “require”, “ensure” or something like that. Its internal logic could be the same as for assert, except that it is never compiled out, of course.

More information

I found John Lakos' talk Defensive Programming Done Right, given at CppCon'14 (1st part, 2nd part) very enlightening. He takes the idea of customizing what assertions are enabled and how to react on failed exceptions even further than I did in this answer.


答:
According to Eric Lippert a Type is

... an abstract quantity that we can manipulate using rules. Like "if T is a type then T[] is also a type", and so on.

The implementation of how a language compiler or runtime implements Types is another thing.  In a compiled language, like C or C# or Java, this checking happens at compile time,  and in Java and C# these checks also happen at runtime.  However, in javascript and Ruby, these checks happen (to my knowledge) exclusively at runtime since no compilation is required.

so how can you "check" the type, other than whether it responds to a particular message?

Dynamic languages deal with types on every single expression that it evaluates because the runtime needs to know the types of the objects that it's interpreting in order to know what to do at all!

In the other good answers here, some examples of badly formed expressions are given, but some other examples also exist.  Think of the difference between == and === in javascript for example.

```<code>console.log('5' == 5)  // true
console.log('5' === 5) // false
</code>```

The javascript runtime needs to check the type of the objects at runtime in order to obey its specification.

Body:
According to Eric Lippert a Type is

... an abstract quantity that we can manipulate using rules. Like "if T is a type then T[] is also a type", and so on.

The implementation of how a language compiler or runtime implements Types is another thing.  In a compiled language, like C or C# or Java, this checking happens at compile time,  and in Java and C# these checks also happen at runtime.  However, in javascript and Ruby, these checks happen (to my knowledge) exclusively at runtime since no compilation is required.

so how can you "check" the type, other than whether it responds to a particular message?

Dynamic languages deal with types on every single expression that it evaluates because the runtime needs to know the types of the objects that it's interpreting in order to know what to do at all!

In the other good answers here, some examples of badly formed expressions are given, but some other examples also exist.  Think of the difference between == and === in javascript for example.

console.log('5' == 5)  // true
console.log('5' === 5) // false

The javascript runtime needs to check the type of the objects at runtime in order to obey its specification.


问:
Microservices REST or AMQP, which case
I've read many articles concerning microservices architecture and I was wondering when to use AMQP or REST.

I've read that loose coupling between services is a good thing and AMQP seems to be a good choice in that case. But if we use AMQP, this means that we do not need REST endpoints anymore (but it means that we lose the HATEOAS concept).

But is REST really a good way to build my services? Cause I won't use any endpoints... In which case one is better than the other one?

When should I use one or the other?

答:
By discarding REST, you lose much more than just HATEOAS. If your microservices are public (and it's a good idea for them to be public or at least tend towards being public one day¹), using anything other than REST and SOAP would be problematic:

Some developers never used AMQP,

Some have used AMQP, but are often much more familiar with REST and SOAP,

AMQP libraries for some languages are not particularly straightforward,

Manual experimentation with the service is very limited: I can use CURL to do any request to Amazon S3; what should I install on my machine if I want to play with an AMQP variant of S3?

Debugging REST and SOAP is easy. I just track the HTTP exchanges and analyze them. Not sure what tools should I use to see to debug AMQP exchanges.

AMQP is great, but it's done for a very specific purpose of exchanges based on events. While it's technically possible to do RPC with AMQP, it's not its primary purpose.

The asynchronous aspect is important too. Sometimes it's a benefit: I don't want to block the user interface of an app while doing requests to servers. Sometimes, it just make things harder than they need to be: if I need to recover a file backup from Amazon S3 because the local one was corrupted, and then restore the backup, my batch file necessarily needs CURL to finish its job before continuing, and a synchronous operation (with a specific timeout) makes perfect sense.

Keep REST for primary operations:

Getting a product,

Storing an invoice,

and use AMQP for the tasks where messaging actually makes sense:

Processing all invoices from September and notify the app when the report is ready to be shown (given that the operation takes usually from two to ten minutes),

The benefit of AMQP here is its asynchronous aspect. An HTTP request pending for ten minutes have a good chance of causing a timeout and other issues.

Dispatching the information that the backups were corrupted to every one who may be interested, such as the support people, the database administrators, the monitoring team, the developers of the application which uses this database, etc.

The benefit of AMQP here is, among others, the ability to add the subscribers without changing the application which tracks backups and triggers the alert when it finds a corrupted one.

¹ A public web service isn't necessarily used by users outside a company. In large or medium-size companies, your service is often used by other divisions of the same company and has the same requirements as the one which would be used by any third party: it should mistrust any call (the fact that some guy you never heard of who calls your service works in the same company you do doesn't mean he will not exploit its security issues), it should be documented properly (because the same Indian guy doesn't necessarily know your phone number and doesn't necessarily know English), etc.

Title: Microservices REST or AMQP, which case

ContentLicense: CC BY-SA 4.0


答:
It's very reasonable to add checks to your code. For plain assert (the one built into C and C++ compiler) my usage pattern is that a failed assert means there is a bug in the code which needs to be fixed. I interpret this a bit generously; if I expect a web request to return a status 200 and assert for it without handling other cases then a failed assertion does indeed show a bug in my code, so the assert is justified.

So when people say an assert that only checks what the code does is superfluous that's not quite right. That assert checks what they think the code does, and the whole point of the assert is to check that the assumption of no bug in the code is right. And the assert can serve as documentation as well. If I assume that after executing a loop i == n and it isn't 100% obvious from the code, then "assert (i == n)" will be helpful.

It's better to have more than just "assert" in your repertoire to handle different situations. For example the situation where I check that something doesn't happen that would indicate a bug, but still continue working around that condition. (For example, if I use some cache then I might check for errors, and if an error happens unexpectedly it may be safe to fix the error by throwing the cache away. I want something that is almost an assert, that tells me during development, and still lets me continue.

Another example is the situation where I don't expect something to happen, I have a generic workaround, but if this thing happens, I want to know about it and examine it. Again something almost like an assert, that should tell me during development. But not quite an assert.

Too many asserts: If an assert crashes your program when it is in the hands of the user, then you must not have any asserts that crash because of false negatives.

Title: Is possible to write too many asserts?

Body:
I am a big fan of writing assert checks in C++ code as a way to catch cases during development that cannot possibly happen but do happen because of logic bugs in my program. This is a good practice in general.

However, I've noticed that some functions I write (which are part of a complex class) have 5+ asserts which feels like it could potentially be a bad programming practice, in terms of readability and maintainability. I think it's still great, as each one requires me to think about pre- and post-conditions of functions and they really do help catch bugs. However, I just wanted to put this out there to ask if there is a better paradigms for catching logic errors in cases when a large number of checks is necessary.

Emacs comment: Since Emacs is my IDE of choice, I have it slightly gray out the assert statements which helps reduce the feeling of clutter that they can provide. Here's what I add to my .emacs file:

```<code>; gray out the "assert(...)" wrapper
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<\\(assert\(.*\);\\)" 1 '(:foreground "#444444") t)))))

; gray out the stuff inside parenthesis with a slightly lighter color
(add-hook 'c-mode-common-hook
  (lambda () (font-lock-add-keywords nil
    '(("\\<assert\\(\(.*\);\\)" 1 '(:foreground "#666666") t)))))
</code>```


答: It depends. If the code requirements are clearly documented, then the assertion should always match the requirements. In which case it is a good thing. However, if there are no requirements or badly written requirements, then it would be hard for new programmers to edit code without having to refer to the unit test each time to figure out what the requirements are.</p>

Title: Is possible to write too many asserts?