问:
Is table inheritance the wrong approach
If we take the two below entities as en example.

```<code>public class Person
{
    public string Username {get;set;}
    public string DisplayName {get;set;}
}

public class Worker:Person
{
    public string Title {get;set}
    public int SecurityId {get;set;}
}
</code>```

When anyone first registers with this app, basic information would be captured and a Person would be created. Once an admin comes along, they may want to assign a role to this Person. Now Roles in the sense of Authorisation are not in question, there is a RoleProvider. However, if I make someone a worker, some additional details need to be captured. How those new details are best stored is what is in question.

I could have a WorkerProperties class with the fields and give Person
--> Worker a 0.1->1 relationship.

I could have all the fields as part of Person and just fill in what
is required. At runtime accessing the Persons role would be needed to
work out what fields would be required.

I could create a Worker as shown above. Inheriting from Person. With
this option there is the problem that the PK is the username
registered with. I would need to somehow change the discriminator
column generated by EF to essentially change the object type to
Worker.

答:
Is 'Worker' really a subtype? If you say 'yes', then that person can't become any other subtype of 'Person', as you can't change the type of an object / entity instance without recreating it and deleting the old one.

If it's not really a subtype, but really another 'Role' a person can take (and I have to say, 'Worker' really sounds like a role), use a role system, so model what a person can do as a separate entity.

The problem is equal to whether a Person should have subtypes like 'Employee' or 'Customer'. If you design it that way, an Employee can't become a Customer. Well, in reality the Employee can of course, but in the DB it's not possible unless you create a new instance of Customer with the same data, which effectively copies the Employee entity instance.

Title: Is table inheritance the wrong approach


问:
How to layer if statements when order of logic is irrelevant?
Basically I have a series of logic in my website that can lead to 5 total outcomes. Basically two different if tests and then a catch all else statement.

For example:

```<code>if cond1:
    if mod1:
        #do things
    elif mod2:
        #do things
elif cond2:
    if mod1:
        #do things
    elif mod2
        #do things
else:
    #do things
</code>```

I was thinking about rewriting it like this:

```<code>if cond1 and mod1:
    #do things
elif cond1 and mod2:
    #do things
elif cond2 and mod1:
    #do things
elif cond2 and mod2:
    #do things
else:
    #do things
</code>```

Is there any real difference in these two coding options/a better choice for this kind of logic testing?

答:
One difference is that cond1 only gets evaluated once in the first code snippet, but can get evaluated twice in the second example if mod2 is false. If cond1 has side effects, that changes the semantics. If cond1 is expensive to evaluate, that could also be a problem even if the semantics don't change.

If neither of those conditions are true, it's largely a matter of taste and style, but I'd argue the second form more clearly highlights the nature of the logic (5 independent cases) whereas the first form requires a bit more effort to see that the 5 cases can be treated separately.

ContentLicense: CC BY-SA 3.0


问:
How to allocate cross-cutting concerns in agile software development planning?
My employer has been moving from traditional waterfall projects to a modified version of agile.  Work is broken into stories, which are estimated and sequenced into two-week long iterations.  Each iteration includes points for building, testing, and accepting features.

Stories are focused on testable business features.  There is no way to plan and account for cross cutting concerns such as design, architecture, infrastructure, or (ironically) project management.

Should agile teams explicitly include stories or tasks for these cross-cutting concerns?  How does your team handle tasks that never go away?  Are they "off book"?

答:
TL:DR; Stories for systems architecture, emergent design through refactoring and code deduplication.

This is what we do at my work:

Systems architecture and infrastructure is treated as a story (or multiple stories), in our parlance it would be a research card.  The research when done answers a question and usually leads to more well defined stories or cards.

Code design is dealt with differently.  We practice emergent design through constant refactoring and code deduplication that is always a part of every programming task we do.

An Aside:

As you may well know refactoring design can be very difficult, especially with an established code base.  One of the biggest mitigating factors for us that makes iterative design even possible is doing Acceptance Test Driven Development.  We create a test suite that defines and tests our systems behavior.  This has allowed us on occasion to completely rip out entire subsystems, reimplement them and still be confident that everything works.  We usually try and do this iteratively and as part of providing customer value.  However, there are exceptions to the rule and when those arise (rarely) we have spent a few days solely on reworking some part of the design.  BUT, that is okay because they are rare occurrences and our process allows for exceptions.


问:
If I use MIT-licensed components in my software, can my customers resell it?
My amateur reading of the MIT license suggests that any software is distributed to my customers containing any MIT-licensed components can be freely re-distributed in its entirety.

Permission is hereby granted [...] to deal in the Software without restriction, including [...] the rights to [...] distribute [...] copies of the Software.

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

It's not clear whether "the Software" refers to the entire application, or just the individual MIT-licensed component.  So which is it?

答:
According to Wikipedia, "the Software" refers to just the MIT-licensed component.

The article claims

It is a permissive free software license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms and the copyright notice. Such proprietary software retains its proprietary nature even though it incorporates software under the MIT License.

Here's the license (from OpenSource.org):

The MIT License (MIT)

Copyright (c) <year> <copyright holders>

Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

I've highlighted the important sentence where it appears to me to define the term "the Software" as "this software and associated documentation files", referring to the component covered by the MIT license.


问:
Testing that an attribute does not exist cannot fail when writing tests before code
I have been taught to follow the Red->Greeen->Refactor pattern when doing TDD. There have been situations where this pattern have not been applicable though.

For instance, a test to make sure that a controller action method (ASP.NET MVC) does not have an Authorize attribute. Since the test is testing the absense of an attribute it will pass on the first go, unless an Authorize attribute is added only to have the test fail.

What I have done so far when testing for absense of said Authorize attribute is to write a test for it, then add the Authorize attribute just to make sure that the test actually works, then immediately remove the Authorize attribute.

Am I doing something wrong, or is this just the way it is; some tests will pass unless we intentionally add code to make the fail and then remove that particular code?

答: So the situation is this: your method does not have an Authorize attribute.  Why do you need to test this?  There are an infinite number of negative assertions like this which could be made about any given entity, all of which are initially true.  If you have a genuine need to test this, it's because it's a genuine problem somewhere - somewhere something is getting objects with a method with an Authorize attribute, and it shouldn't.  That's the point at which to introduce the test.  Not out of the blue.  And that's the point - where you say, "this thing can't work if it's handed an object with a method with an Authorize attribute." where you figure out what should happen if it is handed such an object.  Write that test.  Don't write a test about your controller, which itself is really neutral about the presence or absence of the attribute.  Write the test around the entity which genuinely cares about the attribute.  Then make it pass.</p>


问:
Drawback of using static method
For methods that never access instance variable or static variable and they act just like a function (name-spaced) and they are deterministic base on only the input arguments , I want to ask, are there any consideration if I change all of them to static method?

I keep hearing people saying it static method is poor, but I am looking for some real code example on my above case.

答:
The problem with static methods is mockability and more generally substitutability.  Although there are mocking frameworks which will allow you to mock static methods, there is broader support for mocking a non-static method, and it's simple to do yourself by subclassing.

Say I'm testing class A which interacts with class B.  If it calls only non-static members of B, then I can inject a replacement for B which behaves the way I need, for instance for testing.  But if it calls a static member of B, it's hard (depending on your mocking framework, sometimes impossible) to mock.  So I have to use a real B - or the real B class - in my test of A; now I have a more complicated test, and one which is testing more than the unit (A) I'm interested in.  It's more fragile and harder to reason about than if I can just mock out the method.

I think that's the best rationale for avoiding static methods.

Title: Drawback of using static method


问:
What does "context-free" mean in the term "context-free grammar"?
Given the amount of material that tries to explain what a context-free grammar (CFG) is, I found it surprising that very few (in my sample, less than 1 in 20) give an explanation on why such grammars are called "context-free". And, to my mind, none succeeds in doing so.

My question is, why are context-free grammars called context-free? What is "the context"? I had an intuition that the context could be other language constructs surrounding the currently analyzed construct, but that seems not to be the case. Could anyone provide a precise explanation?

答:
It means all of its production rules have a single non-terminal on their left hand side.

For example, this grammar which recognizes strings of matched parentheses ("()", "()()", "(())()", ...) is context-free:

```<code>S → SS
S → (S)
S → ()
</code>```

The left-hand side of every rule consists of a single non-terminal (in this case it's always S, but there could be more.)

Now consider this other grammar which recognizes strings of the form {a^n b^n c^n : n >= 1} (e.g. "abc", "aabbcc", "aaabbbccc"):

```<code>S  → abc
S  → aSBc
cB → WB
WB → WX
WX → BX
BX → Bc
bB → bb
</code>```

If the non-terminal B is preceded by the terminal/literal character c, you rewrite that term to WB but if it's preceded by b, you expand to bb instead. This is presumably what the context-sensitivity of context-sensitive grammars is alluding to.

A context-free language can be recognized a push-down automaton. Whereas a finite state machine makes use of no auxiliary storage, i.e. its decision is based only on its current state and input, a push-down automaton also has a stack at its disposal and can peek at the top of the stack for taking decisions.

To see that in action, you can parse nested parentheses by moving left to right and pushing a left parentheses onto a stack each time you encounter one, and popping each time you encounter a right parentheses. If you never end up trying to pop from an empty stack, and the stack's empty at the end of the string, the string is valid.

For a context-sensitive language, a PDA isn't enough. You'll need a linear-bounded automaton which is like a Turing Machine whose tape isn't unlimited (though the amount of tape available is proportional to the input). Note that that describes computers pretty well - we like to think of them as Turing Machines but in the real world you can't grab arbitrarily more RAM mid-program. If it's not obvious to you how an LBA is more powerful than a PDA, an LBA can emulate a PDA by using part of its tape as a stack, but it can also choose to use its tape in other ways.

(If you're wondering what a Finite State Machine can recognize, the answer is regular expressions. But not the regexes on steroids with capture groups and look-behind/look-ahead you see in program languages; I mean the ones you can build with operators like [abc], |, *, +, and ?. You can see that abbbz matches regex ab*z just by keeping your current position in the string and regex, no stack required.)

Body:
It means all of its production rules have a single non-terminal on their left hand side.

For example, this grammar which recognizes strings of matched parentheses ("()", "()()", "(())()", ...) is context-free:

S → SS
S → (S)
S → ()

The left-hand side of every rule consists of a single non-terminal (in this case it's always S, but there could be more.)

Now consider this other grammar which recognizes strings of the form {a^n b^n c^n : n >= 1} (e.g. "abc", "aabbcc", "aaabbbccc"):

S  → abc
S  → aSBc
cB → WB
WB → WX
WX → BX
BX → Bc
bB → bb

If the non-terminal B is preceded by the terminal/literal character c, you rewrite that term to WB but if it's preceded by b, you expand to bb instead. This is presumably what the context-sensitivity of context-sensitive grammars is alluding to.

A context-free language can be recognized a push-down automaton. Whereas a finite state machine makes use of no auxiliary storage, i.e. its decision is based only on its current state and input, a push-down automaton also has a stack at its disposal and can peek at the top of the stack for taking decisions.

To see that in action, you can parse nested parentheses by moving left to right and pushing a left parentheses onto a stack each time you encounter one, and popping each time you encounter a right parentheses. If you never end up trying to pop from an empty stack, and the stack's empty at the end of the string, the string is valid.

For a context-sensitive language, a PDA isn't enough. You'll need a linear-bounded automaton which is like a Turing Machine whose tape isn't unlimited (though the amount of tape available is proportional to the input). Note that that describes computers pretty well - we like to think of them as Turing Machines but in the real world you can't grab arbitrarily more RAM mid-program. If it's not obvious to you how an LBA is more powerful than a PDA, an LBA can emulate a PDA by using part of its tape as a stack, but it can also choose to use its tape in other ways.

(If you're wondering what a Finite State Machine can recognize, the answer is regular expressions. But not the regexes on steroids with capture groups and look-behind/look-ahead you see in program languages; I mean the ones you can build with operators like [abc], |, *, +, and ?. You can see that abbbz matches regex ab*z just by keeping your current position in the string and regex, no stack required.)


问:
Passing in config values to a method using SOLID principles
I have an email helper class that has a method that sends email:

```<code>private static class EmailHelper
{
    public static void SendEmail(string from, string to, string subject, string message)
    {
        MailMessage msg = new MailMessage(from, to, subject, body);
        var client = new SmtpClient("my.smpthost.com"); //this will be moved to config.
        client.Send(msg);
    }
}
</code>```

My smtp host string will be placed in my config file. Question is what's the recommended way to pass the smtp host to this method?

Should I have a constructor in this class that takes in the smtp string?

Or, should I pass the smtp as a 5th parameter?

Or should this method directly read from the config?

(I realize that there may be several different ways to do this, but I am trying to understand the recommended approach, or at least approaches that are NOT recommended, keeping in mind the SOLID principles.)

答:
A really easy way out would be to just fob this off onto .NET configuration and use the parameterless constructor which will grab the SMTP settings out of this app's configuration. This will let you inject appropriate values as required and probably the most SOLID thing you could do if you are staying static. See microsoft's man page on System.Net.Mail configuration for more info.

But since you want to learn here I would start by eliminating the whole static method for sending email approach -- it is definitely better than handling all of this by hand anytime you want to send an email. You would be much better served using an interface to provide a facade for sending email and then swapping in implementations as you see fit. So you'll want something like:

```<code>public interface IEmailService
{
    MessageSentResult SendMessage(MailMessage msg);
}

public class MessageSentResult
{
    public bool Successful { get; set; }
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set;}
    public MailMessage SentMessage { get; set; }
    public string FailedRecipients { get; set; }
}
</code>```

Which might have an implementation that looks like:

```<code>    private readonly SmtpClient smtpClient;

    public SystemNetEmailService(SmtpClient smtpClient)
    {
        if (smtpClient == null) throw new ArgumentNullException("smtpClient");
        this.smtpClient = smtpClient;
    }

    public MessageSentResult SendMessage(MailMessage msg)
    {
        if (msg == null) throw new ArgumentNullException("msg");
        var res = new MessageSentResult()
                      {
                          SentMessage = msg,
                      };
        try
        {
            smtpClient.Send(msg);
            res.Successful = true;
            res.ErrorMessage = "No error.";
        }
        catch (SmtpFailedRecipientException mfex)
        {
            res.ErrorCode = mfex.StatusCode.ToString();
            res.ErrorMessage = "Some recipeints failed. See FailedRecipients for details.";
            res.FailedRecipients = mfex.FailedRecipient;
        }
        catch (SmtpException sex)
        {
            res.ErrorCode = sex.StatusCode.ToString();
            res.ErrorMessage = sex.Message;
            res.Successful = false;
        }
        return res;
    }
</code>```

The main advantage here is testability and swappability. Testabiltiy inasmuch as you can easily build a fake implementation that doesn't send mail but could be used in your unit tests to check the message is correct. Swappability meaning you can do things like swap in a completely different implementation like backhauling your mail out over something like mailgun or mandrill because you realized delivery matters.

Body:
A really easy way out would be to just fob this off onto .NET configuration and use the parameterless constructor which will grab the SMTP settings out of this app's configuration. This will let you inject appropriate values as required and probably the most SOLID thing you could do if you are staying static. See microsoft's man page on System.Net.Mail configuration for more info.

But since you want to learn here I would start by eliminating the whole static method for sending email approach -- it is definitely better than handling all of this by hand anytime you want to send an email. You would be much better served using an interface to provide a facade for sending email and then swapping in implementations as you see fit. So you'll want something like:

public interface IEmailService
{
    MessageSentResult SendMessage(MailMessage msg);
}

public class MessageSentResult
{
    public bool Successful { get; set; }
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set;}
    public MailMessage SentMessage { get; set; }
    public string FailedRecipients { get; set; }
}

Which might have an implementation that looks like:

    private readonly SmtpClient smtpClient;

    public SystemNetEmailService(SmtpClient smtpClient)
    {
        if (smtpClient == null) throw new ArgumentNullException("smtpClient");
        this.smtpClient = smtpClient;
    }

    public MessageSentResult SendMessage(MailMessage msg)
    {
        if (msg == null) throw new ArgumentNullException("msg");
        var res = new MessageSentResult()
                      {
                          SentMessage = msg,
                      };
        try
        {
            smtpClient.Send(msg);
            res.Successful = true;
            res.ErrorMessage = "No error.";
        }
        catch (SmtpFailedRecipientException mfex)
        {
            res.ErrorCode = mfex.StatusCode.ToString();
            res.ErrorMessage = "Some recipeints failed. See FailedRecipients for details.";
            res.FailedRecipients = mfex.FailedRecipient;
        }
        catch (SmtpException sex)
        {
            res.ErrorCode = sex.StatusCode.ToString();
            res.ErrorMessage = sex.Message;
            res.Successful = false;
        }
        return res;
    }

The main advantage here is testability and swappability. Testabiltiy inasmuch as you can easily build a fake implementation that doesn't send mail but could be used in your unit tests to check the message is correct. Swappability meaning you can do things like swap in a completely different implementation like backhauling your mail out over something like mailgun or mandrill because you realized delivery matters.


问:
Code re-use in C++, via multiple inheritance or composition? Or...?
I originally asked this question on StackOverflow, but I was directed here, and I think my problem is perhaps as much conceptual as technical, so here goes.

If you’re defining a hierarchy of abstract class in C++, and then creating concrete subclasses with implementations, you could end up with abstract classes something like this, say:

```<code>  A
 / \
B1 B2
</code>```

So the concrete classes then inherit like so:

```<code>B1   B2        B1   B2
 |    |         |    |
C1   C2        D1   D2
</code>```

And this is all fine and dandy when Cn and Dn are just implementing the interfaces of Bn, or where say C1 and C2 implement the A interface differently.

However, if I want to have some shared functionality in C1 and C2, which comes from the A interface, where do I put it?

It can’t go in A, both because A is abstract and because Dn should not be inheriting it.

It seems like there’s a notional A_for_C implementation, but does this belong in another ancestor class? Or in a composed sibling class?

```<code>   _____A_____                       _____A_____
  /     |     \                     /     |     \
B1   A_for_C  B2        vs        B1     B2     A_for_C
 |_____/ \____ |                   |      |
C1            C2                  C1     C2

                               (C1 and C2 then each have an A_for_C and delegate)
</code>```

The first one seems conceptually accurate, but requires virtual inheritance, while the second requires delegation. So both impose a performance hit despite there not being any real ambiguity.

Reading around the web, on this website I find it said

Some people believe that the purpose of inheritance is code reuse. In C++, this is wrong. Stated plainly, “inheritance is not for code reuse.”

How then should the implementation be shared?

Further thoughts

I found some relevant discussion in these questions:

Where does this concept of "favor composition over inheritance" come from?

Interface and Inheritance: Best of both worlds?

Is there any "real" reason multiple inheritance is hated?

I think utnapistim’s answer below is much pithier and to the point than these, and helped me mentally cut through a lot of what these other questions/answers discuss.

Inheritance is about agreeing to fulfil a contract. Multiple inheritance is fine if the subclass really does guarantee fulfilling the parent contracts.

Implementation, however, is only really the concern of the final object. Yes, it might be convenient to inherit the implementation sometimes, but that’s actually orthogonal to the interface, and there are various techniques for pulling in an implementation other than the default v-table-based approach, including:

CRTP as per unaptism’s answer

The template method pattern

(Which are, I think, equivalent except that one is compile-time and one is run-time.)

答:
I think the most of the "inheritance" problems are in its name. Especially when dealing with C++, that as a multiparadigm language does not necessarily have to obey to the OOP paradigms, pattern and terminology.

If viewed aside from any paradigm-specific terminology, C++ offers two "composition" (with plain English memaning) methods:

explicit embedding ( struct A { B m; } a; a.m.fn(); // B::fn )

implicit embedding ( struct A: B {} a; a.fn(); // B::fn )

(I didn't use "composition" and "inheritance" just to don't "distract" into OOP terminology)

The second produce the same data structure layout as the first, it simply makes the m name implicit and makes A to implicitly behave like B. If we don't make virtual function to come into play, this is just a way to import the B defined behavior into A without the need to write more code in A itself.

There is no intention to apply any substitution principle, here. There is no OOP concept in this. This is not what OOP school call "inheritance". It just incidentally have the same name given by the OOP school and the C++ laguage spec.

std::true_type inherits from std::integal_constant. None of them has virtual methods (included the destructor). From a OOP purist this is a blasphemy, but nerveless, it's part of the C++ standard library.

When you make virtual function to come into play, then you acquire the capability to "override" a behavior with another (may be declared as undefined one). This makes C++ classes to become very similar to what OOP school calls "Object", and implicit embedding what they call "inheritance".

But C++ offer another most often ignored "substitution mechanism" (together with virtual functions): DOMINANCE. It is often ignored because is meaning less with single inheritance languages, but plays in multiple inheritance.

Consider this:

```<code>struct Inteface_A
{
    virtual fnA() = 0;
    virtual ~Inteface_A() {};
};

struct Implementation_A_comon
{
    virtual fnA() { cout << "common implementation of IA" << endl; }
    virtual ~Implementation_A_comon() {}
};

struct Implementation_A_special
{
    virtual fnA() { cout << "special implementation of IA" << endl; }
    virtual ~Implementation_A_special() {}
};

class Actual_object:
   public Inteface_A,
   protected Implementation_A_comon,
   public Interface_B, //not declared here, but may be in another header
   protected Implementation_B_common // not declared here, may be in yet another header
{
};

class Another_object:
   public Inteface_A,
   protected Implementation_A_special
{
};
</code>```

Here both Actual_object and Another_object can be valid substitute of Inteface_A, and since fn is pure (abstract, in other literature) a call to ia->fn() makes the call to end-up in the only valid fn method inherited from the derived object. And it is the one provided by the inherited "implementation" inherited (in C++ pure sense) class. This is dominace.

You can easily imagine this extended with a number of different interface and a number of different "partial implementation", inheriting each-other in various way, completing each other providing different behaviors to be imported into a final object.

Is it orthodox OOP? Absolutely no. Is it "valid OOP"? respect to interface yes, respect to implementations no (or at least, not properly).
Is this valid C++: yes. And also a good code reuse, (no implementation to rewrite many many times into every object that has a same interface to implement) using run-time-type polymorphism, staying out from templates and static polymorphism, not adequate where different object type have to coexist into a same runtime context: CRTPs IA and IA are both named IA, have the same interface, but from a runtime perspective are unrelated. You cannot have a std::vector<something> that can refer them both.

Something the pure OOP school simply don't accept just because ... they don trust their own programmers in understanding all this.
But to me... that's their fault, not MI's.

Body:
I think the most of the "inheritance" problems are in its name. Especially when dealing with C++, that as a multiparadigm language does not necessarily have to obey to the OOP paradigms, pattern and terminology.

If viewed aside from any paradigm-specific terminology, C++ offers two "composition" (with plain English memaning) methods:

explicit embedding ( struct A { B m; } a; a.m.fn(); // B::fn )

implicit embedding ( struct A: B {} a; a.fn(); // B::fn )

(I didn't use "composition" and "inheritance" just to don't "distract" into OOP terminology)

The second produce the same data structure layout as the first, it simply makes the m name implicit and makes A to implicitly behave like B. If we don't make virtual function to come into play, this is just a way to import the B defined behavior into A without the need to write more code in A itself.

There is no intention to apply any substitution principle, here. There is no OOP concept in this. This is not what OOP school call "inheritance". It just incidentally have the same name given by the OOP school and the C++ laguage spec.

std::true_type inherits from std::integal_constant. None of them has virtual methods (included the destructor). From a OOP purist this is a blasphemy, but nerveless, it's part of the C++ standard library.

When you make virtual function to come into play, then you acquire the capability to "override" a behavior with another (may be declared as undefined one). This makes C++ classes to become very similar to what OOP school calls "Object", and implicit embedding what they call "inheritance".

But C++ offer another most often ignored "substitution mechanism" (together with virtual functions): DOMINANCE. It is often ignored because is meaning less with single inheritance languages, but plays in multiple inheritance.

Consider this:

struct Inteface_A
{
    virtual fnA() = 0;
    virtual ~Inteface_A() {};
};

struct Implementation_A_comon
{
    virtual fnA() { cout << "common implementation of IA" << endl; }
    virtual ~Implementation_A_comon() {}
};

struct Implementation_A_special
{
    virtual fnA() { cout << "special implementation of IA" << endl; }
    virtual ~Implementation_A_special() {}
};

class Actual_object:
   public Inteface_A,
   protected Implementation_A_comon,
   public Interface_B, //not declared here, but may be in another header
   protected Implementation_B_common // not declared here, may be in yet another header
{
};

class Another_object:
   public Inteface_A,
   protected Implementation_A_special
{
};

Here both Actual_object and Another_object can be valid substitute of Inteface_A, and since fn is pure (abstract, in other literature) a call to ia->fn() makes the call to end-up in the only valid fn method inherited from the derived object. And it is the one provided by the inherited "implementation" inherited (in C++ pure sense) class. This is dominace.

You can easily imagine this extended with a number of different interface and a number of different "partial implementation", inheriting each-other in various way, completing each other providing different behaviors to be imported into a final object.

Is it orthodox OOP? Absolutely no. Is it "valid OOP"? respect to interface yes, respect to implementations no (or at least, not properly).
Is this valid C++: yes. And also a good code reuse, (no implementation to rewrite many many times into every object that has a same interface to implement) using run-time-type polymorphism, staying out from templates and static polymorphism, not adequate where different object type have to coexist into a same runtime context: CRTPs IA<A> and IA<B> are both named IA, have the same interface, but from a runtime perspective are unrelated. You cannot have a std::vector<something> that can refer them both.

Something the pure OOP school simply don't accept just because ... they don trust their own programmers in understanding all this.
But to me... that's their fault, not MI's.


问:
Is it a bad practice to keep database schema scripts (DDL) and manipulation (DML) scripts in different modules
we have a project structure like the following

"module-shared" module depends on "module-database" module and some other modules depend on "module-shared" but no other module depends on "module-database".

All the DML SQL scripts are stored in "module-shared" but DDL are stored in "module-database".

The advantage of this design is that

we don't have to release the database if changes are around DML in "module-shared" and use database integration tests to make sure they are still compatible.

The disadvantage is that

this creates some confusions on the versions. For example you can have "module-shared" 2.3.1 depends on "module-database" 1.4.2 and eventually we will forget which version is compatible with which.

Questions:

Would it be a better design if we have a "module-database" which contains both DDL and DML (and all other database operations if any) and module-shared contains everything it had except database operations?

What's your experiences on having multi-tier architectures? do you always use modules to segregate tiers? Do you have experiences where you may have DAO and Services in the same module? If you do, where did you keep the DDL schema scripts?

UPDATE: forget to mention that the DDL is versioned using database script versioning system such as flyway. So that all DDL changes are incremental

Note: e.g. a module could be gradle module, maven module, etc.

Note: I am trying my best to be not biased while asking this question. So please assume that I don't have any preference on either solution. :)

答:
I'm familiar with storing DDL scripts in repositories that use an ORM (i.e. ruby on rails).

When I've seen DML mixed in with the DML's the results I have seen is:

You can set up a database from scratch using them but you lose the ability to easily go back and forwards for individual steps.


答:
In practice, it is difficult to release a new database version.  While it is nice to have a module with the current DDL, in many cases you will likely be modifying an existing database.  I would keep it as a separate module.

The practice for DDL that I use, is to generate an upgrade (and downgrade) script for each release.  Changes that break the current release (deletions and new constraints) get deferred until the next release.  There are some other consideration that allow two releases to work with a database version.  These scripts include the DML release they apply to in their name.

Most of your DML should work over a wide range of versions.  It is possible that you will have many DML releases without DDL changes.  In other cases, you may have DDL changes to resolve performance issues that have no corresponding DML changes.

If you tag your code in your version control system, it really doesn't matter much which of the two modules changed.  Unless you check-in a version identifier,  it is OK to have multiple tags on the same code.

EDIT: I've taken a quick look at flyway. I don't think it significantly alters the above recommendations.  I would suggest making your application DML dependencies allow the DDL version to increase.  I wouldn't want to break my application by adding an index, column, or table.  (DDL changes may include DML to update data which should be in the same repository as the DDL.)

Consider deprecating columns and tables that are being dropped.  You should be able to use text search on the DML to identify and remove use deprecated objects.  This should allow you to test some regressions without having to regress the database.

Title: Is it a bad practice to keep database schema scripts (DDL) and manipulation (DML) scripts in different modules

Body:
we have a project structure like the following

"module-shared" module depends on "module-database" module and some other modules depend on "module-shared" but no other module depends on "module-database".

All the DML SQL scripts are stored in "module-shared" but DDL are stored in "module-database".

The advantage of this design is that

we don't have to release the database if changes are around DML in "module-shared" and use database integration tests to make sure they are still compatible.

The disadvantage is that

this creates some confusions on the versions. For example you can have "module-shared" 2.3.1 depends on "module-database" 1.4.2 and eventually we will forget which version is compatible with which.

Questions:

Would it be a better design if we have a "module-database" which contains both DDL and DML (and all other database operations if any) and module-shared contains everything it had except database operations?

What's your experiences on having multi-tier architectures? do you always use modules to segregate tiers? Do you have experiences where you may have DAO and Services in the same module? If you do, where did you keep the DDL schema scripts?

UPDATE: forget to mention that the DDL is versioned using database script versioning system such as flyway. So that all DDL changes are incremental

Note: e.g. a module could be gradle module, maven module, etc.

Note: I am trying my best to be not biased while asking this question. So please assume that I don't have any preference on either solution. :)


问:
How can one manage thousands of IF...THEN...ELSE rules?
I am considering building an application, which, at its core, would consist of thousands of if...then...else statements. The purpose of the application is to be able to predict how cows move around in any landscape. They are affected by things like the sun, wind, food source, sudden events etc.

How can such an application be managed? I imagine that after a few hundred IF-statements, it would be as good as unpredictable how the program would react and debugging what lead to a certain reaction would mean that one would have to traverse the whole IF-statement tree every time.

I have read a bit about rules engines, but I do not see how they would get around this complexity.

答:
I don't think you should define so many if-else statements. From my point of view your problem has multiple components:

It should be async or multithreaded, because you have multiple cows with different personalities, different configuration. Each cow asks herself which direction to go in before its next move. In my opinion a sync code is a poor tool for this problem.

The configuration of the decision tree constantly changes. It depends on the position of the actual cow, the weather, the time, the terrain, etc... Instead of building a complex if-else tree, I think we should reduce the problem to a wind rose or a direction - weight function:

figure 1 - direction - weight functions for some of the rules

The cow should always go to the direction which has the greatest sum weight. So instead of building a big decision tree you can add a set of rules (with different direction - weight functions) to each cow, and simply process the result by each time you ask the direction. You can reconfigure those rules by every position change, or by passing of the time, or you can add these details as parameters, every rule should get. It is an implementation decision. The simplest way to get a direction, to add a simple loop from 0° to 360° with 1° step. After that you can count the sum weight of each 360 direction and run through a max() function to get the proper direction.

You don't necessarily need a neural network to do this, just one class for each rule, one class for the cows, maybe for the terrain, etc... and one class for the scenario (for example 3 cows with different rules & 1 specific terrain).

figure 2 - cow app async decision nodes and connections

red for messaging direction - weight map through the rules

blue for orientation and position updates after decision making

green for input updates after orientation and position update

black for getting inputs

note: you'll probably need a messaging framework to implement something like this

So if making learning cows is not part of your problem, you don't need a neural network or genetic algorithms. I am not an expert of AI, but I guess if you want to adapt your cows to the real ones, then you can do it simply with a genetic algorithm and the proper set of rules. If I understand well, you need a population of cows with random rule settings. After that you can compare the behavior of real cows to the behavior of your model population and keep 10% which walk the closest path to the real ones. After that you can add new rule configuration constraints to your cow factory based on the 10% you kept, and add new random cows to the population, and so on, until you got a model cow which behaves just like the real ones...


问:
Storing and accessing settings from database query
I am trying to figure out the best way to accomplish this so feel free to criticize my thought process.

My tool has different locales and each locale can have different settings for the tool. For example, Arizona could have the top 5 stats turned on where as California does not.

I pull all of the settings based on the locale and have an array of the data:

```<code>    SimpleXMLElement Object
(
    [settings] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [settingName] => Home Page Stats
                    [settingDescription] => Show the Top 5 Teammate / Teamleader stats?
                    [requireValue] => 0
                    [localeID] => 14
                    [status] => 1
                    [value] => SimpleXMLElement Object
                        (
                        )

                    [settingID] => 3
                )

            [1] => SimpleXMLElement Object
                (
                    [settingName] => Test
                    [settingDescription] => Testing
                    [requireValue] => 1
                    [localeID] => 14
                    [status] => 1
                    [value] => 66
                    [settingID] => 5
                )

        )

)
</code>```

What I need to be able to do though is get information based on a current setting. They will never be in the same order so I can't do it by location in the array. I need to be able to access the data based on the setting name.

I have tried a few things with iterating over the array and getting the value I need at that time but it seems like its not a great way to do it.

Is there a better way to store / access this data?

I just need to be able to say If setting name "Home page stats has a status of 1 then then get me its value.

I feel like I may be making this more complicating than it should be.

答:
Have you tried setting a key in an associative array?  Each site get's a unique identifier and you grab the site specific value with $o->setting[$siteID] would give you the proper setting object? Granted it would be possible for code running on a site to potentially query the settings for a different site.  If [settings] was also a SimpleXMLElement Object you could use and xpath query to find the right element.

```<code>SimpleXMLElement Object
(
    [settings] => Array
        (
            [Home Page] => SimpleXMLElement Object
                (
                    [settingName] => Home Page Stats
                    [settingDescription] => Show the Top 5 Teammate / Teamleader stats?
                    [requireValue] => 0
                    [localeID] => 14
                    [status] => 1
                    [value] => SimpleXMLElement Object
                        (
                        )

                    [settingID] => 3
                )

            [Test] => SimpleXMLElement Object
                (
                    [settingName] => Test
                    [settingDescription] => Testing
                    [requireValue] => 1
                    [localeID] => 14
                    [status] => 1
                    [value] => 66
                    [settingID] => 5
                )
            [Another Site] => SimpleXMLElement Object
                (
                    [settingName] => Another Site
                    [settingDescription] => Another Site
                    [requireValue] => 1
                    [localeID] => 14
                    [status] => 1
                    [value] => 66
                    [settingID] => 5
                )
        )
)
</code>```

Beyond that, have you thought about having a small config file (.ini, .json, or .xml) for each site and just read it as you load the site? Or move to a pure SimpleXML structure instead of intermixing an array into it?  It would make the whole structure traversable with xpath (though it may be more process intensive than the functionality is worth).

Body:
Have you tried setting a key in an associative array?  Each site get's a unique identifier and you grab the site specific value with $o->setting[$siteID] would give you the proper setting object? Granted it would be possible for code running on a site to potentially query the settings for a different site.  If [settings] was also a SimpleXMLElement Object you could use and xpath query to find the right element.

SimpleXMLElement Object
(
    [settings] => Array
        (
            [Home Page] => SimpleXMLElement Object
                (
                    [settingName] => Home Page Stats
                    [settingDescription] => Show the Top 5 Teammate / Teamleader stats?
                    [requireValue] => 0
                    [localeID] => 14
                    [status] => 1
                    [value] => SimpleXMLElement Object
                        (
                        )

                    [settingID] => 3
                )

            [Test] => SimpleXMLElement Object
                (
                    [settingName] => Test
                    [settingDescription] => Testing
                    [requireValue] => 1
                    [localeID] => 14
                    [status] => 1
                    [value] => 66
                    [settingID] => 5
                )
            [Another Site] => SimpleXMLElement Object
                (
                    [settingName] => Another Site
                    [settingDescription] => Another Site
                    [requireValue] => 1
                    [localeID] => 14
                    [status] => 1
                    [value] => 66
                    [settingID] => 5
                )
        )
)

Beyond that, have you thought about having a small config file (.ini, .json, or .xml) for each site and just read it as you load the site? Or move to a pure SimpleXML structure instead of intermixing an array into it?  It would make the whole structure traversable with xpath (though it may be more process intensive than the functionality is worth).


答:
To understand the distinction and the terminology better, it's a good idea to contrast a context-free language like anbn with a context-sensitive one like anbncn. (Notation: a, b, and c are literals here and the exponent n means repeating the literal n times, n>0, say.) For instance, aabbc or aabbbcc is not in the latter language, whereas aabbcc is.

An acceptor for the context-free language anbn can contract a pair of a and b regardless what's around it (i.e. regardless of the context in which ab appears) and it will function correctly, accepting only strings in the language and rejecting anything else, i.e. the grammar is S -> aSb | ab. Note that there are no terminals on the left side of the production(s). (There are two production rules, but we're just writing them compactly.) The acceptor can basically make a local, context-free decision.

In contrast, you can't do something like that for the context-sensitive language anbncn, because for latter you must remember somehow the context you were in, i.e. how many contractions of ab you do to match them with contractions of bc. A grammar for the latter language is

```<code>S -> abc | aBSc
Ba -> aB
Bb -> bb
</code>```

Note that you have both terminals and non-terminals on the left in the last two rules. The terminals on the left are the context in which the non-terminals can be expanded.

Bootnote regarding "contract" vs. "expand" terminology etc.: although the formal grammars are [formally, hah] generative, the way they're actually implemented in parsers is actually reductionist, i.e. you contact everything to a non-terminal, basically applying the rules "in reverse", which is why even the first grammar given above is not practical in a program (it would give you the famous shift-reduce conflict because you can't decide which rule to apply), but the above two grammars suffice for illustrating the distinction between context-free and context-sensitive. The issue of ambiguity in context-free grammars is rather complicated, and not really the topic of this question so I'm not going to say more here, especially since it turns out that Wikipedia has a decent article on that. In contrast its articles on context-free and especially the one on context-sensitive language are !@#$@!#$ especially if you are new to the topic... I guess that's more on my TODO list.

Title: What does "context-free" mean in the term "context-free grammar"?

Body:
Given the amount of material that tries to explain what a context-free grammar (CFG) is, I found it surprising that very few (in my sample, less than 1 in 20) give an explanation on why such grammars are called "context-free". And, to my mind, none succeeds in doing so.

My question is, why are context-free grammars called context-free? What is "the context"? I had an intuition that the context could be other language constructs surrounding the currently analyzed construct, but that seems not to be the case. Could anyone provide a precise explanation?

Body:
To understand the distinction and the terminology better, it's a good idea to contrast a context-free language like anbn with a context-sensitive one like anbncn. (Notation: a, b, and c are literals here and the exponent n means repeating the literal n times, n>0, say.) For instance, aabbc or aabbbcc is not in the latter language, whereas aabbcc is.

An acceptor for the context-free language anbn can contract a pair of a and b regardless what's around it (i.e. regardless of the context in which ab appears) and it will function correctly, accepting only strings in the language and rejecting anything else, i.e. the grammar is S -> aSb | ab. Note that there are no terminals on the left side of the production(s). (There are two production rules, but we're just writing them compactly.) The acceptor can basically make a local, context-free decision.

In contrast, you can't do something like that for the context-sensitive language anbncn, because for latter you must remember somehow the context you were in, i.e. how many contractions of ab you do to match them with contractions of bc. A grammar for the latter language is

S -> abc | aBSc
Ba -> aB
Bb -> bb

Note that you have both terminals and non-terminals on the left in the last two rules. The terminals on the left are the context in which the non-terminals can be expanded.

Bootnote regarding "contract" vs. "expand" terminology etc.: although the formal grammars are [formally, hah] generative, the way they're actually implemented in parsers is actually reductionist, i.e. you contact everything to a non-terminal, basically applying the rules "in reverse", which is why even the first grammar given above is not practical in a program (it would give you the famous shift-reduce conflict because you can't decide which rule to apply), but the above two grammars suffice for illustrating the distinction between context-free and context-sensitive. The issue of ambiguity in context-free grammars is rather complicated, and not really the topic of this question so I'm not going to say more here, especially since it turns out that Wikipedia has a decent article on that. In contrast its articles on context-free and especially the one on context-sensitive language are !@#$@!#$ especially if you are new to the topic... I guess that's more on my TODO list.


问:
Should I use session or cache to keep the time it last polled when polling to server at intervals?
I'm building a web chat app using session to keep the time the app last polled so that the server can determine whether messages exist between the current polling time and last polling time. It works well however, there are few instances whereby the messages sent from client A is not received by client B or the same message is produced twice on client B. Of course, the messages are not lost, always stored in the db after they are sent.

I'm wondering, is this related to my usage of session storage whereby the last and current polling time of both clients are always different(due to session data not being accessible by other user/client)? Or should I change to cache storage so that the last and current polling time of both clients to the server are always the same?

p.s. I'm using Apache server and MySQL though with AJAX setTimeout() function to poll the server at regular intervals.

答:
It sounds like there is a poll happening about the same time as message is submitted.  If that is the case a subsequent poll will not get a message added very close but after the poll.  Have you tried adding some wiggle room to the polltime?  Instead of getting messages after last poll get messages after last poll -1 second then give the polling client some logic to trim messages it already received? What are you using to track submission/poll time, how precise is it?

Also you if your messages are being given a auto-incrementing primary key instead of passing back the last poll time you may want to give it the last message key.  There is no precision gap in consistently incrementing whole numbers.


问:
What should be in a coding standard?
What should be in a good (read:useful) coding standard?

Things the code should have.

Things the code shouldn't have.

Should the coding standard include definitions of things the language, compiler, or code formatter enforces?

What about metrics like cyclomatic complexity, lines per file, etc?

答:
I like the Google JavaScript Style Guide.

Its concise in its guidelines yet has details if you need them.

ContentLicense: CC BY-SA 2.5

Title: What should be in a coding standard?


答:
The answers above give a pretty good definition of what it is. Let's see if I can put it in my own words, so that you will have 23 explanations instead of 20. The whole purpose of a grammar, any grammar, is to figure out if a particular sentence is a sentence in the given language. However, what we really use grammars and parsing for is to figure out what the sentence means. It's like the old diagramming of a sentence you may or may not have done back in English class back in school. A sentence is made of a subject part and a predicate part, a subject part has a noun and maybe some adjectives, a predicate part has a verb and perhaps an object noun, with some more adjectives, etc.

If there were a grammar for English (and I don't think there is, not in the computer science sense) then it would have rules of the following form, called productions.

```<code>Sentence -> SubjectPart PredicatePart
SubjectPart -> Adjective Noun
</code>```

etc...

You could then write a program and hand it any sentence, and the program could use the grammar to figure out which part of the sentence each word is, and what relation they have to each other.

If in every production, there is only one thing on the left side, then that means that whenever you see the right side in the sentence, you are allowed to substitute in the left side. For instance whenever you saw adjective noun, you could say "That's a SubjectPart" without paying any attention to anything outside of that phrase.

However, English (even the simplified description of English I gave above) is context-sensitive. "Adjective noun" isn't always a SubjectPart, it could be a NounPhrase in a PredicatePart. It depends on the context. Let's expand our pseudo-English grammar a bit:

```<code>Sentence -> SubjectPart PredicatePart
SubjectPart -> Adjective Noun
PredicatePart -> VerbPhrase ObjectNounPhrase
VerbPhrase ObjectNounPhrase -> VerbPhrase Adjective Noun
</code>```

You can only make an "adjective noun" into an ObjectNounPhrase if it comes right after a VerbPhrase.

Basically, if you have a production and you can apply it any time you want, no matter what surrounds it, it is context-free.

You can always tell if a grammar is context free easily. Just check if there is more than one symbol on the left side of the arrows.

Any language might be described by more than one grammar. If some grammar for a language is context-free, the language is context free. It can be proven for some languages that there is no context-free grammar possible. I suppose there might be a context-free grammar for the simplified pseudo-English subset I am describing above.

As for why it matters, it requires a simpler kind of program to parse a context-free grammar. As noted in the other answers, it doesn't require the full power of a Turing machine to parse a context-free grammar. A lookahead LR(1) parser (which is a kind of pushdown machine) for a particular context-free grammar can parse any sentence in that grammar in time and space linear to the length of the sentence. If the sentence is in the language, the parser will produce a structure tree identifying what each symbol in the sentence means (or at least what part it plays in the structure). If the sentence is not in the grammar, the parser will notice and stop on the first symbol which is impossible to reconcile with the grammar and preceding symbols (on the first "error").

What's even better is that there are programs which you can give a description of a grammar, and a list of instructions about what to do with each part (in a sense attaching a "meaning" to each production) and the program will write the parser for you. The program will parse the sentence, find the structure, and run your instructions on each part of the structure. This kind of program is called a parser-generator or compiler-compiler.

This kind of language analysis was invented for automatic analysis of natural language (such as English) but it turns out that this is most useful for analyzing computer languages. A language designer can write a grammar which captures his new language, then run it through the parser-generator to get a program which parses his language, and translates, interprets, compiles, executes, etc if he wants.

In fact, in most cases you can't really do this. For instance, balanced parentheses are a context-free language, but a language where it is required to declare all variables before you use them is context-sensitive. The parser is a part of the compiler, but additional logic is required to enforce these other requirements. What you then have to do is write a grammar which captures as much of your language as possible, run that through a parser-generator, then write code which enforces the rest of the requirements (symbol table handler, etc).

We don't generally use context-sensitive grammars because they are much more poorly supported. I don't know if there is an equivalent to an LR(k) parser-generator for context-sensitive languages. Yes, a Turing machine (or linear bound machine) can parse one, but I don't know if there is a general algorithm for turning a context-sensitive grammar into a program for a Turing machine, in the sense that an LR(1) generator makes parse tables for a pushdown machine. My guess is that the tables which underlie the parser would be exponentially larger. In any case, CS students (like myself, back in the day) are usually taught context-free grammars and LR(1) parser generators such as YACC.

Body:
The answers above give a pretty good definition of what it is. Let's see if I can put it in my own words, so that you will have 23 explanations instead of 20. The whole purpose of a grammar, any grammar, is to figure out if a particular sentence is a sentence in the given language. However, what we really use grammars and parsing for is to figure out what the sentence means. It's like the old diagramming of a sentence you may or may not have done back in English class back in school. A sentence is made of a subject part and a predicate part, a subject part has a noun and maybe some adjectives, a predicate part has a verb and perhaps an object noun, with some more adjectives, etc.

If there were a grammar for English (and I don't think there is, not in the computer science sense) then it would have rules of the following form, called productions.

Sentence -> SubjectPart PredicatePart
SubjectPart -> Adjective Noun

etc...

You could then write a program and hand it any sentence, and the program could use the grammar to figure out which part of the sentence each word is, and what relation they have to each other.

If in every production, there is only one thing on the left side, then that means that whenever you see the right side in the sentence, you are allowed to substitute in the left side. For instance whenever you saw adjective noun, you could say "That's a SubjectPart" without paying any attention to anything outside of that phrase.

However, English (even the simplified description of English I gave above) is context-sensitive. "Adjective noun" isn't always a SubjectPart, it could be a NounPhrase in a PredicatePart. It depends on the context. Let's expand our pseudo-English grammar a bit:

Sentence -> SubjectPart PredicatePart
SubjectPart -> Adjective Noun
PredicatePart -> VerbPhrase ObjectNounPhrase
VerbPhrase ObjectNounPhrase -> VerbPhrase Adjective Noun

You can only make an "adjective noun" into an ObjectNounPhrase if it comes right after a VerbPhrase.

Basically, if you have a production and you can apply it any time you want, no matter what surrounds it, it is context-free.

You can always tell if a grammar is context free easily. Just check if there is more than one symbol on the left side of the arrows.

Any language might be described by more than one grammar. If some grammar for a language is context-free, the language is context free. It can be proven for some languages that there is no context-free grammar possible. I suppose there might be a context-free grammar for the simplified pseudo-English subset I am describing above.

As for why it matters, it requires a simpler kind of program to parse a context-free grammar. As noted in the other answers, it doesn't require the full power of a Turing machine to parse a context-free grammar. A lookahead LR(1) parser (which is a kind of pushdown machine) for a particular context-free grammar can parse any sentence in that grammar in time and space linear to the length of the sentence. If the sentence is in the language, the parser will produce a structure tree identifying what each symbol in the sentence means (or at least what part it plays in the structure). If the sentence is not in the grammar, the parser will notice and stop on the first symbol which is impossible to reconcile with the grammar and preceding symbols (on the first "error").

What's even better is that there are programs which you can give a description of a grammar, and a list of instructions about what to do with each part (in a sense attaching a "meaning" to each production) and the program will write the parser for you. The program will parse the sentence, find the structure, and run your instructions on each part of the structure. This kind of program is called a parser-generator or compiler-compiler.

This kind of language analysis was invented for automatic analysis of natural language (such as English) but it turns out that this is most useful for analyzing computer languages. A language designer can write a grammar which captures his new language, then run it through the parser-generator to get a program which parses his language, and translates, interprets, compiles, executes, etc if he wants.

In fact, in most cases you can't really do this. For instance, balanced parentheses are a context-free language, but a language where it is required to declare all variables before you use them is context-sensitive. The parser is a part of the compiler, but additional logic is required to enforce these other requirements. What you then have to do is write a grammar which captures as much of your language as possible, run that through a parser-generator, then write code which enforces the rest of the requirements (symbol table handler, etc).

We don't generally use context-sensitive grammars because they are much more poorly supported. I don't know if there is an equivalent to an LR(k) parser-generator for context-sensitive languages. Yes, a Turing machine (or linear bound machine) can parse one, but I don't know if there is a general algorithm for turning a context-sensitive grammar into a program for a Turing machine, in the sense that an LR(1) generator makes parse tables for a pushdown machine. My guess is that the tables which underlie the parser would be exponentially larger. In any case, CS students (like myself, back in the day) are usually taught context-free grammars and LR(1) parser generators such as YACC.


问:
Deleting dynamic elements from a database
I have a select dropdown, with '+' and '-' buttons that add and remove items before submission.

I would like to be able to remove the elements with the '-' button after they have been added to the database.

I'm not sure how to go about doing this, other than removing prior entries and rewriting the options again.

Ideally, it would be reusable and simple to figure for the other developer on the team, or anyone who may replace me down the line. Can someone point me in the right direction?

答:
So many ways to do this, especially if you have JS. On click of a negative call a function that looks up the id of that record and adds it to an array of hidden inputs then hides it from the list of records.

```<code><input type='hidden' name='remove[]' value=$id>
</code>```

When you submit the form have it walk the remove array and do the delete queries.  With PDO you could do it with a single statement and bindParam().

Without JS it is harder but doable.  Have the x be a submit button on it's own with a value the PHP is looking for seperate from an full form update, delete the individual record from the db then reload the forms.

Another way is to use CSS to reskin a checkbox with a deactivated and activated delete icon.  Then you can look for checked inputs it in your form processing.  Of the 3 I have not actually implemented it myself.

Body:
So many ways to do this, especially if you have JS. On click of a negative call a function that looks up the id of that record and adds it to an array of hidden inputs then hides it from the list of records.

<input type='hidden' name='remove[]' value=$id>

When you submit the form have it walk the remove array and do the delete queries.  With PDO you could do it with a single statement and bindParam().

Without JS it is harder but doable.  Have the x be a submit button on it's own with a value the PHP is looking for seperate from an full form update, delete the individual record from the db then reload the forms.

Another way is to use CSS to reskin a checkbox with a deactivated and activated delete icon.  Then you can look for checked inputs it in your form processing.  Of the 3 I have not actually implemented it myself.


答:
Declaring a pure functions as static is correct in my opinion.  It would be awkward to require creating an instance of a stateless object just to call a function.

There are cases however where you need them to be in an object instance.  For example when you pass that function to another method, as you do with a Comparator in a sort method.  More generally, when you need to substitute your function, or a set of functions by another one, you'll need an instance.

The bad reputation of static methods comes from when they are used as a substitute for the Singleton pattern.  But in this case, there is some state stored in static variables.

Title: Drawback of using static method

Body:
For methods that never access instance variable or static variable and they act just like a function (name-spaced) and they are deterministic base on only the input arguments , I want to ask, are there any consideration if I change all of them to static method?

I keep hearing people saying it static method is poor, but I am looking for some real code example on my above case.


问:
Running time of simple for-loops
I'm reading algorithms and I understand most of it, one thing that I can still struggle with a lot is something as simple as running times on different for-loops. Everyone seems to have easy with that, except for me and therefore I search help here.

I am currently doing some excercises from my book and I need help completing them in order to figure out the different running times.

The title of the exercise is: "Give the order of growth(as a function of N) of the running times of each of the following code fragments"

a:

```<code>int sum = 0;
for (int n = N; n > 0; n /= 2)
  for(int i = 0; i < n; i++)
    sum++;
</code>```

b:

```<code>int sum = 0;
for (int i = 1; i < N; i *= 2)
  for(int j = 0; j < i; j++)
    sum++;
</code>```

c:

```<code>int sum = 0;
for (int i = 1; i < N; i *= 2)
  for(int j = 0; j < N; j++)
    sum++;
</code>```

We have learned different kinds of running times/order of growth like n, n^2, n^3, Log N, N Log N etc. But I have hard understanding which to choose when the for loop differs like it does. the "n, n^2, n^3" is not a problem though, but I can't tell what these for-loops running time is.

Here's an attempt of something.. the y-axis represents "N" value and the x axis represents times the outer loop has been run. The drawings in the left is: arrow to the right = outer-loop, circle = inner loop and the current N value. I have then drawn some graphs just to look at it but I'm not sure this is right though.. Especially the last one where N remains 16 all the time. Thanks.

答:
Background

For an arbitrary for loop such as:

for (int p = …; …)
    do_something(p);
```

<p>it should be clear that the run time of this loop is simply the sum of the run times of the inner computations (i.e. <code>do_something(p)</code> in this case).  Note that the run time of the inner computation <em>may</em> depend on the loop variable(s).</p>

<p>In the special case where the run time of <code>do_something(p)</code> is independent of the loop variable(s), the run-time is then proportional to the number of times the inner computation is executed.</p></li>
<li><p>Typically, simple arithmetic such as incrementing (<code>sum++</code>) are constant-time operations.</p></li>
<li><p>For brevity I will use <code>log</code> to denote the base-2 logarithm.  Additionally, I will use <code>pow(x, y)</code> to denote <code>x</code> raised to the power <code>y</code> because <code>^</code> is often used for something else in the C-family of languages.</p></li>
</ul>

<h1>The problems</h1>

<p>The interesting coincidence in this set of problems is that the run time of each computation is actually proportional to the final value of the <code>sum</code> (can you see why?) so the question can be simplified to: how does the final value of <code>sum</code> vary with the parameter <code>N</code>?</p>

<p>The <code>sum</code> can be calculated algebraically, but we don't need to know the exact result.  We just need to make some good <em>estimates</em>.</p>

<h2>Problem A</h2>

<pre class="lang-c prettyprint-override"><code>int sum = 0;
for (int n = N; n > 0; n /= 2)
  for (int i = 0; i < n; i++)
    sum++;
</code>```

How many times does the outer loop run?  It starts at N and goes down by half each time until it hits zero.  This is just (a discrete version of) an exponential decay with a base of 2.  Therefore, we can make an educated guess that

```<code>n ∝ 1 / pow(2, p)    [approximately]
</code>```

Here, we define p to be a counter that increases by 1 each time the outer loop is repeated.  In fact, this is exactly what your graph plots.

Where does p start?  We can just pick p_start = 0 for convenience, and this allows us to determine the coefficient of proportionality:

```<code> n ≈ N / pow(2, p)
</code>```

Where does p end?  Whenever n reaches zero!  Since this is integer division, n can only be zero if N < pow(2, p).  From this we can deduce that p_end ≈ log(N) (base-2 logarithm).  With experience, you can easily skip this entire analysis and jump straight to this conclusion instead.

Now we can rewrite the loop using the variable p instead of n (again, approximately).  Notice that every instance of n must be substituted:

int sum = 0;
for (int p = 0; p < log(N); p++)
  for (int i = 0; i < N / pow(2, p); i++)
    sum++;
```

<p>The advantage of writing the loop like this is that it becomes obvious how many times the outer loop is repeated.  (Keen readers may notice that this is </p>

<p>The inner loop consists of only increments to <code>sum</code> and is repeated <code>N / pow(2, p)</code> times, so we can just rewrite the above to:</p>

<pre class="lang-c prettyprint-override"><code>int sum = 0;
for (int p = 0; p < log(N); p++)
  sum += N / pow(2, p);
</code>```

(Note that the run time of this loop may no longer be the same, but the value of sum still reflects the run time of the original problem.)

From this code we can write the value of sum as:

(As randomA noted, this is just a geometric series so there is a well-known closed-form expression for the sum.  Here I use a more general technique based on calculus, however.)

This can be simplified further by approximating the summation as an integral:

And there you go, the run time of the problem A is linear with respect to N.

Problem B

int sum = 0;
for (int i = 1; i < N; i *= 2)
  for (int j = 0; j < i; j++)
    sum++;
```

<p>The problem here is similar, but I'll omit some of the steps.  The variable <code>i</code> grows exponentially, so we can do the transformation:</p>

```i ≡ pow(2, p)
```

<p>with <code>p</code> increasing by one at each iteration, starting from <code>0</code>, and ending at <code>log(N)</code>.  After variable substitution, the loop becomes:</p>

<pre class="lang-c prettyprint-override"><code>int sum = 0;
for (int p = 0; p < log(N); p++)
  for (int j = 0; j < pow(2, p); j++)
    sum++;
</code>```

which reduces to:

int sum = 0;
for (int p = 0; p < log(N); p++)
  sum += pow(2, p);
```

<p>You can apply the same tricks again to find a closed-form expression for the sum: it is also <code>O(N)</code>.</p>

<h2>Problem C</h2>

<pre class="lang-c prettyprint-override"><code>int sum = 0;
for (int i = 1; i < N; i *= 2)
  for (int j = 0; j < N; j++)
    sum++;
</code>```

This one is actually quite a bit easier because the number of repeats of the inner loop doesn't depend on the outer loop variable, so we can go right away and simplify this to:

int sum = 0;
for (int i = 1; i < N; i *= 2)
  sum += N;
```

<p>The loop has the same exponential behavior as in Problem B, so it is run only <code>log(N)</code> times, so this can then be simplified to:</p>

<pre class="lang-c prettyprint-override"><code>int sum = 0;
sum += log(N) * N;
</code>```

Hence, the run time is O(N log(N)).

Title: Running time of simple for-loops

Body:
Background

For an arbitrary for loop such as:

for (int p = …; …)
    do_something(p);

it should be clear that the run time of this loop is simply the sum of the run times of the inner computations (i.e. do_something(p) in this case).  Note that the run time of the inner computation may depend on the loop variable(s).

In the special case where the run time of do_something(p) is independent of the loop variable(s), the run-time is then proportional to the number of times the inner computation is executed.

Typically, simple arithmetic such as incrementing (sum++) are constant-time operations.

For brevity I will use log to denote the base-2 logarithm.  Additionally, I will use pow(x, y) to denote x raised to the power y because ^ is often used for something else in the C-family of languages.

The problems

The interesting coincidence in this set of problems is that the run time of each computation is actually proportional to the final value of the sum (can you see why?) so the question can be simplified to: how does the final value of sum vary with the parameter N?

The sum can be calculated algebraically, but we don't need to know the exact result.  We just need to make some good estimates.

Problem A

int sum = 0;
for (int n = N; n > 0; n /= 2)
  for (int i = 0; i < n; i++)
    sum++;

How many times does the outer loop run?  It starts at N and goes down by half each time until it hits zero.  This is just (a discrete version of) an exponential decay with a base of 2.  Therefore, we can make an educated guess that

n ∝ 1 / pow(2, p)    [approximately]

Here, we define p to be a counter that increases by 1 each time the outer loop is repeated.  In fact, this is exactly what your graph plots.

Where does p start?  We can just pick p_start = 0 for convenience, and this allows us to determine the coefficient of proportionality:

 n ≈ N / pow(2, p)

Where does p end?  Whenever n reaches zero!  Since this is integer division, n can only be zero if N < pow(2, p).  From this we can deduce that p_end ≈ log(N) (base-2 logarithm).  With experience, you can easily skip this entire analysis and jump straight to this conclusion instead.

Now we can rewrite the loop using the variable p instead of n (again, approximately).  Notice that every instance of n must be substituted:

int sum = 0;
for (int p = 0; p < log(N); p++)
  for (int i = 0; i < N / pow(2, p); i++)
    sum++;

The advantage of writing the loop like this is that it becomes obvious how many times the outer loop is repeated.  (Keen readers may notice that this is

The inner loop consists of only increments to sum and is repeated N / pow(2, p) times, so we can just rewrite the above to:

int sum = 0;
for (int p = 0; p < log(N); p++)
  sum += N / pow(2, p);

(Note that the run time of this loop may no longer be the same, but the value of sum still reflects the run time of the original problem.)

From this code we can write the value of sum as:

(As randomA noted, this is just a geometric series so there is a well-known closed-form expression for the sum.  Here I use a more general technique based on calculus, however.)

This can be simplified further by approximating the summation as an integral:

And there you go, the run time of the problem A is linear with respect to N.

Problem B

int sum = 0;
for (int i = 1; i < N; i *= 2)
  for (int j = 0; j < i; j++)
    sum++;

The problem here is similar, but I'll omit some of the steps.  The variable i grows exponentially, so we can do the transformation:

i ≡ pow(2, p)

with p increasing by one at each iteration, starting from 0, and ending at log(N).  After variable substitution, the loop becomes:

int sum = 0;
for (int p = 0; p < log(N); p++)
  for (int j = 0; j < pow(2, p); j++)
    sum++;

which reduces to:

int sum = 0;
for (int p = 0; p < log(N); p++)
  sum += pow(2, p);

You can apply the same tricks again to find a closed-form expression for the sum: it is also O(N).

Problem C

int sum = 0;
for (int i = 1; i < N; i *= 2)
  for (int j = 0; j < N; j++)
    sum++;

This one is actually quite a bit easier because the number of repeats of the inner loop doesn't depend on the outer loop variable, so we can go right away and simplify this to:

int sum = 0;
for (int i = 1; i < N; i *= 2)
  sum += N;

The loop has the same exponential behavior as in Problem B, so it is run only log(N) times, so this can then be simplified to:

int sum = 0;
sum += log(N) * N;

Hence, the run time is O(N log(N)).


问:
Why are these seemingly unnecessary merges happening in git?
Consider this screenshot from our development repository:

We are relatively new to git, so things are still somewhat confusing. The question at hand: If you take a look at the commits by me at the very top; are confusing to us. Why do I need to merge something if I didn't even branch anything?

I commited the adjust buildpath commit, and after that, git immediately made me do a merge. but with what? The invitation branch is not interesting for me, and I never touched it in any way.

Where did this anonymous blue branch come from and why? My colleague (blue avatar) only works in the invitation branch currently.

Can someone explain to me why this is happening in git-layman terms (as I said, we are new to this)?

答:
I find the site Visualizing Git Concepts with D3 very helpful to see how the tree will look when various git commands are done from various states.

Lets back track to the Disabled mail delivery... commit.

The next commit was on the invitation branch done by Red as origin/master was merged into that.

Unfortunately teal was still on the master branch and did two commits on master - Removed duplicate imports... and Moved user routes... which were then merged into invitation again by red.

Now, you were also working on what you had locally as master and did the adjust buildpath commit.  However, when trying to push this some where it said that your master was out of sync with the remote - and it was.  Master on remote was at Moved user routes and thus you had to merge the remote back into what you had.

git merge also does a commit when it does its merge.

From the D3 link at the top, the git merge is very close to the state you had at the adjust buildpath commit.  Doing git merge master in your tree is much like doing a git merge dev in the D3 sandbox:

And then a git merge dev brings us to:

Commit e065536... is exactly like your Merge branch 'master' of https://... in this case.

But what if you don't want to have those commits.  Some people don't like them (personally, I do... but that is my preference).

Then, you are looking at git rebase

This will reapply the commits from one branch on another.

Note again the very similar structure as the merge example (note: I've checked out master rather than leave it on dev).  And then a git rebase dev brings everything into line without the additional commit.

Note that the commit bb92e0e which was the old master head is now greyed out and the new master head is decfd13 because the history is reapplied on top of what you have done.

There's a gotcha there.  You are rewriting your local history when you do a rebase.  If you have shared the state of your repo (pushing it to somewhere else) where commit bb92e0e is out there, rebasing will confuse everyone.  If you have to do a git push --force, you're probably doing it wrong.

Note that when you do a git pull, you are doing the commands git fetch and git merge - thus the additional commit.  You can do a git pull --rebase which will be a rebase rather than a merge for the second step (you can also tweak your git config to do this by default).  You can play with this a bit in the D3 site 'git pull' example.

Note that the convention on your tree appears to be pull and merge rather than rebase - it may be best to keep following that convention and just understand (and accept) where the commits are coming from.


问:
Is it ok to write "extra" unit tests?
My understanding of how TDD should work is that you write a failing test for the next bit of functionality you want to add to a function or object, code until the test passes and then write the next test. Is it ever ok to write tests that pass with the code as is?

One example of that happened today. I was writing a function that could Manchester encode an arbitrary number of bits. I wrote failing tests for encoding one single bit and coded until it passed, then wrote a failing test for passing two bits to the function and coded until it passed. But the solution I used to handle two bits made the code work for any number of bits. Because passing a byte to the function will be it's most common use, I added a unit test to make sure it worked for 8 bits, which did in fact pass.

Did I violate TDD principles? Is there anything wrong with adding redundant tests just for my peace of mind? I understand part of the problem is that I could have written a faulty tests and would never know because it didn't fail in the first place, but I'm not sure what the alternative is.

答:
The main reasons for using TDD are to make sure every bit of code you write is at least minimally exercised by the test suite, and that your API is well-usable for the application programmer.

Writing an additional test for a case that already passes doesn't increase coverage, and it doesn't change the API any further, so neither of those reasons apply - the test doesn't add any value in these respects, but it certainly does not harm either. It just takes up time to write that you might have spent doing something else.

Nevertheless, it's perfectly possible to have algorithms that work on simple cases and even look as if they were completely general, but in fact aren't, so there is nothing wrong in principle with adding another test case for N=8. In a perfect world you might have thought about that case right away and written both tests before coding the solution, but doesn't really matter very much if you add it afterwards - you've still fulfilled all the princples that people want TDD for.

(There are those who demand that you write exactly one test case and then exactly one bit of code, and that every test tests exactly one thing, i.e. that every defect in your code base would trip exactly one test. But I see no added value in such exaggerated cycle-observance.)

Title: Is it ok to write "extra" unit tests?


问:
What should every programmer know about programming?
Please, stay on technical issues, avoid behavior, cultural, career or political issues.

答: Data structures</p>

Body: Data structures


问:
How do we add software to a machine?
When we build a new machine, how do we add software to that machine?

I know we have assemblers and compilers that convert the high-level code into machine code for it to understand. But having designed a new machine with some new architecture, how do we proceed ahead and add assembler and compilers to a machine understanding only machine language?

As far as I know, we do not write the assemblers or compilers in machine language, so how do we add these programs to the new machine so that it can run programs in high-level language?

答:
As far as I know, we do not write the assemblers or compilers in machine language, so how do we add these programs to the new machine so that it can run programs in high-level language?

As a matter of fact we do, at least if there is no other development chain available for cross-compilation. The first modern computers didn't have one, so yes, people wrote assemblers in machine language, then compilers in assembly language, and finally application programs in higher-level languages. Google "bootstrapping" for more information.

Today, of course, it is very rare that no cross-compiling development chain is available, since there are multiple free or almost-free compiler kits out there that have portability as one of their main goals. In fact, it's unlikely that we will ever go back to the times when new machines have no option to cross-develop anything! The chain of program-transforming programs goes back in history all the way to the beginning of compilers, much like all life today is ultimately descended from the same cells eons ago, and losing it would be a catastrophe similar to killing off all higher life and having to let nature redevelop it from single-cell organisms. But at least in principle, yes, compilers have to be arduously implemented at a level below the one they're supposed to work with.

Title: How do we add software to a machine?


答:
I feel like static method's encourage behavior like this. In this case we have a global class with a static function. We are hiding the fact that Foo depends on StaticWorker.DoWork().

Static Method

```<code>public class Foo
{
    public void Bar()
    {
        StaticWorker.DoWork();
    }
}
</code>```

On the other hand, instance-level methods encourage passing the dependent object. Which is better than reaching into a global.

Instance Method

```<code>public class Foo
{
    Worker Worker;

    public Foo(Worker worker)
    {
        this.Worker = worker;
    }

    public void Bar()
    {
        this.Worker.DoWork();
    }
}
</code>```

Now of course you could pass in a function, but I still like the abstraction I get with objects.

Another huge benefit of instance-level methods is that the class can implement an interface which you cannot do for a static method.

This is similar to the singleton argument. Singleton's themselves don't cause damage if used properly, but it makes it easier for people to call the singleton all over their code without passing it, once again creating invisible dependencies and global state.

There are exceptions to the rule. Sometimes you have a small, lightweight method. It will never change, and is not a dependency for anything else, I might make it static. You have to use your best judgement on a case by case basis, but I would say favor instances, especially if you have any doubts.

I feel like there are several benefits to using instance methods and all I have to do is instantiate an object. A small price to pay for the rewards.

Title: Drawback of using static method

Body:
I feel like static method's encourage behavior like this. In this case we have a global class with a static function. We are hiding the fact that Foo depends on StaticWorker.DoWork().

Static Method

public class Foo
{
    public void Bar()
    {
        StaticWorker.DoWork();
    }
}

On the other hand, instance-level methods encourage passing the dependent object. Which is better than reaching into a global.

Instance Method

public class Foo
{
    Worker Worker;

    public Foo(Worker worker)
    {
        this.Worker = worker;
    }

    public void Bar()
    {
        this.Worker.DoWork();
    }
}

Now of course you could pass in a function, but I still like the abstraction I get with objects.

Another huge benefit of instance-level methods is that the class can implement an interface which you cannot do for a static method.

This is similar to the singleton argument. Singleton's themselves don't cause damage if used properly, but it makes it easier for people to call the singleton all over their code without passing it, once again creating invisible dependencies and global state.

There are exceptions to the rule. Sometimes you have a small, lightweight method. It will never change, and is not a dependency for anything else, I might make it static. You have to use your best judgement on a case by case basis, but I would say favor instances, especially if you have any doubts.

I feel like there are several benefits to using instance methods and all I have to do is instantiate an object. A small price to pay for the rewards.


问:
What's a "Polymorphic method"?
Sometimes people use the phrase "Polymorphic method/function".

Does it mean:

A method that takes a Polymorphic type as a parameter, and performs some operation on it. By "Polymorphic type" I mean a super-type with multiple sub-types.

An abstract or virtual method in a super-type, with multiple sub-types that implement/override the method differently.

答:
The therm "polymorphic", alone, means nothing more that "a noun or verb that can act differently depending on context".

You say "do" and something gets done. What is actually done ... depend on the something.

How this translated into programming depends on the chosen language, its features and the way you use those features to manipulate things.

Even C (that's not normally thought as an OOP language) can use a statement like a.(*do)() to do different things depending on a...

Title: What's a "Polymorphic method"?


答:
If the test is covering behaviour that is valuable, and you want to guard against regressions, then it's a perfectly good idea to write it 'after the fact'.

Imagine that someone else had already written the code without tests. You wouldn't be asking whether it's a bad idea to add tests to existing code.

Title: Is it ok to write "extra" unit tests?

Body:
My understanding of how TDD should work is that you write a failing test for the next bit of functionality you want to add to a function or object, code until the test passes and then write the next test. Is it ever ok to write tests that pass with the code as is?

One example of that happened today. I was writing a function that could Manchester encode an arbitrary number of bits. I wrote failing tests for encoding one single bit and coded until it passed, then wrote a failing test for passing two bits to the function and coded until it passed. But the solution I used to handle two bits made the code work for any number of bits. Because passing a byte to the function will be it's most common use, I added a unit test to make sure it worked for 8 bits, which did in fact pass.

Did I violate TDD principles? Is there anything wrong with adding redundant tests just for my peace of mind? I understand part of the problem is that I could have written a faulty tests and would never know because it didn't fail in the first place, but I'm not sure what the alternative is.


问:
Why are packed structures not part of the C language?
Every C compiler offers the option to "pack" C structures (e.g. __attribute__ ((__packed__)), or #pragma pack()). Now, we all know that packing is required, if we'd like to send or store data in a reliable way. This must also have been a requirement since the first days of the C language.

So I wonder why packed structures are not part of the C language specification? They're not even in C99 or C11 even though the necessity of having them is known for decades now? What I am missing? Why is it compiler specific?

答:
I guess it's because it's depending on the combination of target CPU / compiler used. This means that it's better to be a compiler directive (as it's related to that) than a language aspect, because how to spec that? The only way they could do it is with union.

Raymond's article gives some insight in why this is: http://www.catb.org/esr/structure-packing/


问:
How do I test my code in Python other than by doing it by hand?
I am used to user testing in Java, and I also manually test each section of code I write, but now, I want to automate it.

There is no GUI for this project, so user testing is not required and I can focus code testing. The fact is, I don't know how to test code other than by calling the methods by hand, passing different parameters to them, and check the return value.

I suppose automation is a solution, but don't have a clue how to pass from manual testing to automated one. Are there tools which can create the relevant tests for me, or do I need to write tests manually? What can be automated?

Here is an example of code I want to test. Do I need to transform it somehow in order for it to be unit tested?

```<code>def netInfoToSend(tm, our_or_ip_version, our_or_addr_len, our_op_ip, version_their_ips,
                  num_their_ips, len_their_ips, their_ips):

    cellNetInfopkt = struct.pack(">I", time.time())

    #         Number of addresses    [1 byte]
    # cellNetInfopkt += struct.pack("B", num_their_ips)
    #         Their OR's addresses    [variable]
    print "peerAddress", peerAddress
    print "peerAddress type", type(peerAddress)

    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack(">B", 4)
    cellNetInfopkt += struct.pack("B" * len(peerAddress), *peerAddress)

    cellNetInfopkt += struct.pack(">B", 1)

    # Address format is a type/length/value
    #         This OR's address     [variable]
    cellNetInfopkt += struct.pack(">B", our_or_ip_version) # IPV4
    cellNetInfopkt += struct.pack(">B", our_or_addr_len)
    cellNetInfopkt += struct.pack("B" * len(ownAddress), *ownAddress)

    return cellNetInfopkt
</code>```

答:
Unit testing 101. Using a framework such as the one recommended (https://docs.python.org/2/library/unittest.html) you write a test function that calls the tested function and checks that it works correctly. You do this for each function and each meaningful combination of data values.

There are plenty of good docs and tutorials out there to get you going.