答:
To answer your question about declaring their type; the variables' types have to be known at compile-time, even before it knows which constructor it will use.

When declaring those variables, to be able to call the methods you'd like (Jump(), Move(), Die()) on both of them, you need to declare them as being the most-specific object type you know of them; but not SO specific that it will restrict you from declaring them as the opposite type. Here's an example:

```<code>Shape shape1;
Shape shape2;

shape1 = new Rectangle(); // This works, because a Rectangle extends off of Shape.
shape2 = new Circle(); // This also works, because a Circle extends off of Shape.
shape1 = new Circle(); // Now shape1 has been changed to be a circle, too. The original
// Rectangle just basically disappeared.
</code>```

As for defining the classes "Shape", "Rectangle", and "Circle", like your "Player" class? Well, if all of this sounds new to you, you definitely need to read up on the concept of Polymorphism. I've given you kind of an abstract overview just to give you an idea of what it allows, but mainly it's meant to keep you from needing to copy-paste lots of code, or have large "if-is-type" or "if-is-state" checks of your objects.

Title: C# - initialize variable inside method and use in whole class

Body:
this is a conceptual question, but if i initialize a variable in c# as public will it be able to be used in the class as I want a variable "player1" and a variable "player2" where either could be one of the two (or more)

Player

Computer

Here is what i would like to know how I would do:

```<code>public class Game
{
    //equivalent of initializing it here
    public bool islogging;
    public string[] log;
    public int draws, round;

    public Game(player p1, computer p2)
    {
        public player player1 = p1;
        public computer player2 = p2;
    }
    //other overloads here...
    ...
}
</code>```

trying this it doesn't work as the public keyword is rejected

```<code>public Game(player p1, player p2 )
{
     public  player player1, player2;
     player player3 = p1;
     player player4 = p2;

 }
</code>```

Body:
To answer your question about declaring their type; the variables' types have to be known at compile-time, even before it knows which constructor it will use.

When declaring those variables, to be able to call the methods you'd like (Jump(), Move(), Die()) on both of them, you need to declare them as being the most-specific object type you know of them; but not SO specific that it will restrict you from declaring them as the opposite type. Here's an example:

Shape shape1;
Shape shape2;

shape1 = new Rectangle(); // This works, because a Rectangle extends off of Shape.
shape2 = new Circle(); // This also works, because a Circle extends off of Shape.
shape1 = new Circle(); // Now shape1 has been changed to be a circle, too. The original
// Rectangle just basically disappeared.

As for defining the classes "Shape", "Rectangle", and "Circle", like your "Player" class? Well, if all of this sounds new to you, you definitely need to read up on the concept of Polymorphism. I've given you kind of an abstract overview just to give you an idea of what it allows, but mainly it's meant to keep you from needing to copy-paste lots of code, or have large "if-is-type" or "if-is-state" checks of your objects.


问:
Benefits of TOGAF or similar?
I can read the website blurb and be impressed by the alleged benefits, but I haven't worked anywhere or with anyone who followed the TOGAF (or any alternative) architecture framework.

Our organisation has declared itself dedicated to moving from what is currently a fairly shambolic design & development model towards something approaching a modern structured process.

Things like TOGAF have been mentioned as helping achieve a world-class enterprise development environment (!) but I'm convinced that no-one here really understands the real-world benefits that wholesale adoption might bring and, perhaps more importantly, the effort/pain required to achieve the same.

Do you have experience in using TOGAF or similar to wrestle control in an organisation?  Do you think that use of the framework brought any benefit?

Edit:  For clarification TOGAF is "The Open Group Architecture Framework", a detailed method and set of tools for developing an enterprise architecture.  See: http://www.opengroup.org/architecture/togaf8-doc/arch/

答:
I suppose usage of TOGAF or similar becomes useful when the company and especially its ICT landscape hits some big size. One really big company (employs +25k people and has stack of +100 various IT systems) where I was doing my internship is using TOGAF. And it's concepts and approaches are referenced in architecture defining papers throughout projects they do.

One of the benefits that I could really feel - is that they have common language for numerous stakeholders that are involved on development-architecture-business layers.

Another point that is stated in TOGAF is that you will need to adapt things TOGAF has (like ADM) for your company's scope - then you will get "our organization's architectural framework" which will have good genes so to say.

ContentLicense: CC BY-SA 2.5

Title: Benefits of TOGAF or similar?

ContentLicense: CC BY-SA 3.0


问:
Sending e-mail from a web application without being filtered out
For a web application I'm working on right now it's very important that automated e-mails arrive at the recipient. I've set up the mail server on the VPS that the application is going to run on. I've taken all the regular precautions to make sure that the e-mails it sends are not going to be filtered out: SPF, DKIM, e-mails have both a plain text and html part, html part is valid html etc. etc.

Still some services - in particular Microsofts outlook.net addresses - either block the message or automatically mark it as junk mail. I've read up a little on how Microsoft determines if a message is junk and in our case it's most likely the reputation of the mail server. Since it's a new server it doesn't have any reputation yet.

How do other developers deal with this type of problem? Do you use external SMTP services like Google Apps to send mail from your application? Any ideas or tips?

答: If mailing is important for your app consider to use mailing service like Sendgrid, Mandrill, Mailgun etc. It will save your time and most likely will work more reliably than self-configured mailing service.</p>


问:
Multithreading: am I doing it wrong?
I'm working on an application that plays music.

During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling note.play() freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.)

This kind of behavior creates many threads during playback of a piece of music.

For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes.

So the pseudo-code for playing a progression looks like this:

```<code>void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            runOnNewThread( func(){ note.play(); } );
}
</code>```

So assuming the progression has 4 chords, and we play it twice, than we are opening 3 notes * 4 chords * 2 times = 24 threads. And this is just for playing it once.

Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this.

But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?

答:
A classic approach for this music problem would be to use exactly two threads. One, a lower priority thread would handle the UI or sound generating code like

```<code>void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            otherthread.startPlaying(note);
}
</code>```

(note the concept of only starting the note asynchronously and going on without waiting for it to finish)

and the second, realtime thread would consistently look at all the notes, sounds, samples, etc that should be playing now; mix them and output the final waveform. This part may be (and often is) taken from a polished third party library.

That thread would often be very sensitive to "starvation" of resources - if any actual sound output processing is blocked for longer than your sound card buffered output, then it will cause audible artifacts such as interruptions or pops. If you have 24 threads that are directly outputing audio, then you have a much higher chance that one of them will stutter at some point. This is often considered unacceptable, as humans are rather sensitive to audio glitches (much more than to visual artifacts) and notice even minor stuttering.

Title: Multithreading: am I doing it wrong?

Body:
A classic approach for this music problem would be to use exactly two threads. One, a lower priority thread would handle the UI or sound generating code like

void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            otherthread.startPlaying(note);
}

(note the concept of only starting the note asynchronously and going on without waiting for it to finish)

and the second, realtime thread would consistently look at all the notes, sounds, samples, etc that should be playing now; mix them and output the final waveform. This part may be (and often is) taken from a polished third party library.

That thread would often be very sensitive to "starvation" of resources - if any actual sound output processing is blocked for longer than your sound card buffered output, then it will cause audible artifacts such as interruptions or pops. If you have 24 threads that are directly outputing audio, then you have a much higher chance that one of them will stutter at some point. This is often considered unacceptable, as humans are rather sensitive to audio glitches (much more than to visual artifacts) and notice even minor stuttering.


问:
Ajax call or js to update a cart price
I am building a cart in Java and would like to give users the ability to update the quantity and see the new price instantly. I am using BigDecimal on the back-end for complete accuracy, but the ajax call introduces a slight delay. It isn't much but I could make the update instant by sending the update to the server and just updating the price in Javascript before it even returns. The speed would be wonderful but it comes at the expense of rounding errors being presented to the user.

Now the back-end computed price would be the one shown on the payment page so that would be accurate at least but is the speed worth the risk of a bad value showing in the cart in an eCommerce system?

答:
If you let the math for one  second aside, the following should answer your question:
The webpage, your client received is nothing more than a view. If you want to "display" changes immediately to your customer, you could do the math in JS. No roundtrip to the server needed. Think of oyur system under load: 100 000 people add and delete items on their shopping card. The result is unnecessary background noise on your server to calculate the new sum. What a waste of ressources.

Calculate and display the result via JS for the client and do the real math on the server, when the order is done.

Title: Ajax call or js to update a cart price


问:
Using Django without a database
Is Django a good solution for creating applications that won't use any database and communicate only through an internal API? </p>

答: Django comes with inbuilt sqllite database. Which doesn't require much configurations. And when it comes to the use django without database then it simply violates the MTV pattern of Django. </p>

Title: Using Django without a database


问:
Overloading Methods With Different Behavior - Style
I have a style question about overloading methods/constructors. I have a constructor which
does something very simple, and then calls a method with some side effects. Sometimes however I don't want the side effects so I made a separate overloaded constructor. I show two versions here. Version 1 is simple: if I pass any bool then TrickyFunction won't be called. But maybe that's confusing, because the value of no_tricks does not affect the behavior (only that no_tricks exists). Version 2 actually does process no_tricks and makes a decision to run TrickyFunction based on that.

Which version, or another version, is more stylistically "correct?"

```<code>public foo MyFunction(string a)
{
    variable = a
    TrickyFunction(a)
}

#Version 1
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
}

#Version 2
public foo MyFunction(string a, bool no_tricks)
{
    variable = a
    if (notricks == true)
    {
        TrickyFunction(a)
    }
}
</code>```

答: While C# does not allow a type to have multiple constructors except by giving them all different signatures, types can have any number of factory methods.  My inclination would be to have a protected constructor with a "noTricks" parameter, but have consumers of the class use factory methods to construct instances.  Tricky and non-tricky methods can then be given different names to clarify their behavior.</p>


问:
Is it better to put an event on the top object or closer to where it's local?
Take the following basic structured code for example:

```<code>class Player
{
   public QuestLog QuestLog { get; set; }
}
</code>```

Let us consider that "QuestLog" has the ability to fire off some events when things are added or removed from it. Normally, I would subscribe directly to the QuestLog, such as doing something like:

```<code>player.QuestLog.AcceptedQuest += SomeHandler
</code>```

However, I want to pass in some extra context (the player object). I saw a couple options.

Creating a lambda handler function which can resolve an extra parameter to the handler. This works but has some quirks I don't like. I'm currently using this approach.

I could couple the QuestLog to a Player, passing a reference of the player it belongs to in and fire events off accordingly with it. Feels like needless coupling.

Expose the event on the Player object itself as well as the QuestLog and 'bubble' the event up into where the context is available, thus allowing subscriptions directly onto player.

Keep in mind a player may have a few collections and a few events, so moving them all up might cause a couple dozen events to be held on one class.

How is this usually handled?

答:
Creating a lambda handler function which can resolve an extra parameter to the handler. This works but has some quirks I don't like. I'm currently using this approach.

What don't you like? By keeping the signature small, and letting the handler be aware of the things it needs (but the event firing object needs to not know) you very effectively separate knowledge to where it needs to go.

I could couple the QuestLog to a Player, passing a reference of the player it belongs to in and fire events off accordingly with it. Feels like needless coupling.

Since players already have QuestLogs, then I'd argue that the coupling already exists to some degree. Further, if your handler wants to know that, that just reinforces that notion.

Coupling isn't always bad. Some things really should depend on one another and a clean design will couple those things together cohesively so that it's simple, clean, and robust.

Expose the event on the Player object itself as well as the QuestLog and 'bubble' the event up into where the context is available, thus allowing subscriptions directly onto player.

Sometimes good, but often a sign that you've got the event in the wrong place. This leaks implementation details (or at least it would if you didn't have QuestLog on the player publically, encouraging users to violate the Law of Demeter...).

But getting back to my comment, events have largely fallen out of favor for doing non-UI logic. Events, by their nature cause temporal coupling (you need to do things at the right time, in the right order for them to work properly). Events protect invariants poorly, and tend to leak through abstractions. They're fragile, they're fairly hard to test, they require some mediator to add/remove the event, they're the primary cause of memory leaks...

More often, delegates (or the dependencies themselves) are passed directly into the constructor so that the handler is known at construction time. You can't misuse the class if it's built to work from the start.

That or things work on a pull rather than push mechanism. Something checks the state every frame or some other timeframe (optionally checking some dirty flag which is pushed). This makes it easier to ignore the timing of things in many cases, making parallelism much more viable.


问:
What optimizations can be done for soft real-time code in C#?
I'm writing a soft real-time application in C#. Certain tasks, like responding to hardware requests coming in from a network, needs to be finished within a certain amount of milliseconds; however it is not 100% mission-critical to do so (i.e. we can tolerate it being on time most of the time, and the 1% is undesirable but not a failure), hence the "soft" part.

Now I realize that C# is a managed language, and managed languages aren't particularly suited for real-time applications. However, the speed in which we can get things done in C#, as well as the language features, like reflection and memory management, make the task of building this application much easier.

Are there any optimizations or design strategies one can take to reduce the amount of overhead and increase determinism? Ideally I would have the following goals

Delay the garbage collection until it is "safe"

Allow the garbage collector to work without interfering with real-time processes

Thread/process priorities for different tasks

Are there any ways to do these in C#, and are there any other things to look out for with regards to real-time when using C#?

The platform target for the application is .NET 4.0 Client Profile on Windows 7 64-bit, with. I've set it currently to Client profile but this was just the default option and wasn't chosen for any particular reason.

答:
Take the same approach that games development does in a managed environment and try to minimise object creation / death down to the absolute minimum.

e.g. Try to create all the objects likely to be required at the start and pool obsessively,
pass by ref whereever possible, avoid operations that create short term intermediate objects


答:
The optimization that fulfills your first two bullets is called an Object Pool.  It works by

creating a pool of objects when the program starts,

maintaining references to those objects in a list so that they don't get garbage collected,

handing objects to your program from the pool as needed, and

returning objects back to the pool when you're done using them.

You can find an example class that implements an Object Pool using a ConcurrentBag here.

Thread/process priority can easily be set at runtime.  The Thread Class has methods and properties that allow you to set priority and processor affinity.  The Process Class contains similar facilities.

Title: What optimizations can be done for soft real-time code in C#?

Body:
I'm writing a soft real-time application in C#. Certain tasks, like responding to hardware requests coming in from a network, needs to be finished within a certain amount of milliseconds; however it is not 100% mission-critical to do so (i.e. we can tolerate it being on time most of the time, and the 1% is undesirable but not a failure), hence the "soft" part.

Now I realize that C# is a managed language, and managed languages aren't particularly suited for real-time applications. However, the speed in which we can get things done in C#, as well as the language features, like reflection and memory management, make the task of building this application much easier.

Are there any optimizations or design strategies one can take to reduce the amount of overhead and increase determinism? Ideally I would have the following goals

Delay the garbage collection until it is "safe"

Allow the garbage collector to work without interfering with real-time processes

Thread/process priorities for different tasks

Are there any ways to do these in C#, and are there any other things to look out for with regards to real-time when using C#?

The platform target for the application is .NET 4.0 Client Profile on Windows 7 64-bit, with. I've set it currently to Client profile but this was just the default option and wasn't chosen for any particular reason.


答:
TOGAF certification is great for getting you an interview.

After that I am not too sure of its value.

The main thrust of TOGAF is about standardizing terminology and the various architecture diagrams. Which is in itself a good thing BUT its very vague about what should go into the diagrams and what practical use can be made of them.

Also I find it difficult to take seriously any standard which comes from the organisation responsible for the CORBA fiasco.

I would seriously recommend the TOGAF course book to anyone who has trouble sleeping. The repetitive style with pages full of the same statement re-worded five different ways make it impossible for me to keep my eyes open for more than four pages. :-)

As far as Enterprise Architecture is concerned Zachman is still king of the heap.

Title: Benefits of TOGAF or similar?

Body:
I can read the website blurb and be impressed by the alleged benefits, but I haven't worked anywhere or with anyone who followed the TOGAF (or any alternative) architecture framework.

Our organisation has declared itself dedicated to moving from what is currently a fairly shambolic design & development model towards something approaching a modern structured process.

Things like TOGAF have been mentioned as helping achieve a world-class enterprise development environment (!) but I'm convinced that no-one here really understands the real-world benefits that wholesale adoption might bring and, perhaps more importantly, the effort/pain required to achieve the same.

Do you have experience in using TOGAF or similar to wrestle control in an organisation?  Do you think that use of the framework brought any benefit?

Edit:  For clarification TOGAF is "The Open Group Architecture Framework", a detailed method and set of tools for developing an enterprise architecture.  See: http://www.opengroup.org/architecture/togaf8-doc/arch/


问:
Having an inherited function return the derived type instead of the base type
I am writing two classes in C#:

A Matrix class that represents a general Matrix with n-by-m dimensions

A SquareMatrix class that inherits from Matrix and has the constraint of being n-by-n

The reason I designed it this way is because square matrices support additional specific operations like calculating the determinant or the inverse, so being able to guarantee that those functions are avaliable with the specific type you're using are nice things to have. Additionally it would support all the regular Matrix operations and can be used as a Matrix

I have a function in Matrix called getTranspose(). It calculates the transpose of the Matrix and returns it as a new Matrix

I inherited it in SquareMatrix, but because the transpose of a square matrix is guaranteed to be square matrix, I also want it to return a SquareMatrix

I am unsure about the best way to do this.

I can re-implement the function in SquareMatrix, but that would be code duplication because it's essentially the same calculation

I can use implicit typecast operators, but if I understand correctly that would cause unnecessary allocations (upcast SquareMatrix to Matrix, create a new Matrix as the transpose, create a new SquareMatrix during typecasting and throw away the tranposed Matrix)

I can use explicit typecast operators, but it would be stupid to have to typecast the transpose of a SquareMatrix explicitly, and it also has the same problem of the implicit operator with unnecessary allocations

Is there another option? Should I change the design of having SquareMatrix inherit from Matrix?

This problem also applies to operators. It seems that I have to either implement typecasting operators which might cost in performance, or have to re-implement the same code.

答:
Inheritance not helping to eliminate repetition and typecasts is often a sign that generics would help.  You can do something like:

```<code>public T getTranspose<T>()
// or non-member function
T getTranspose<T>(T input)
</code>```

I haven't fully worked it out, but it seems it might get awkward on the calling side.  I know C# does some inference with generic methods, but I don't know C#, so I'm not familiar with the details.  That might be the way you have to go, though, if you want full compile-time type checking with the least amount of repetition in the implementation.

Another option would be to create private helper functions, then pass in the result type you want, for the helper to populate, like:

```<code>public SquareMatrix getTranspose() {
    SquareMatrix result = new SquareMatrix();
    transposeHelper(result);
    return result;
}
</code>```

This gives you more boilerplate on the implementation side, but at least it isn't full repetition.

A third option is just to check if the result is square in the Matrix implementation, and return a SquareMatrix if it is, like:

```<code>public Matrix getTranspose() {
   Matrix result;
   if (resultIsSquare())
        result = new SquareMatrix();
   else
        result = new Matrix();

   // calculate result
   return result;
}
</code>```

This has the advantage of not needing any implementation at all for getTranspose() in SquareMatrix, but at the expense of requiring type checking of the return value at the call site.  It also works for cases like multiplying two non-square matrices that happen to give a square result.  You give up most compile-time type checking, though.

If your application happens to mostly require run-time instead of compile-time type checking anyway, you might as well just give up the different types and throw an exception if you call a method that a non-square matrix doesn't support.  I believe this is the approach most existing libraries take, especially since there are other conditions than being non-square that can cause methods like inverse() to fail.

Speaking of libraries, there are a lot of good ones out there for matrix math, that are already heavily tested and optimized.  Don't reinvent the wheel if you don't have to.

Body:
Inheritance not helping to eliminate repetition and typecasts is often a sign that generics would help.  You can do something like:

public T getTranspose<T>()
// or non-member function
T getTranspose<T>(T input)

I haven't fully worked it out, but it seems it might get awkward on the calling side.  I know C# does some inference with generic methods, but I don't know C#, so I'm not familiar with the details.  That might be the way you have to go, though, if you want full compile-time type checking with the least amount of repetition in the implementation.

Another option would be to create private helper functions, then pass in the result type you want, for the helper to populate, like:

public SquareMatrix getTranspose() {
    SquareMatrix result = new SquareMatrix();
    transposeHelper(result);
    return result;
}

This gives you more boilerplate on the implementation side, but at least it isn't full repetition.

A third option is just to check if the result is square in the Matrix implementation, and return a SquareMatrix if it is, like:

public Matrix getTranspose() {
   Matrix result;
   if (resultIsSquare())
        result = new SquareMatrix();
   else
        result = new Matrix();

   // calculate result
   return result;
}

This has the advantage of not needing any implementation at all for getTranspose() in SquareMatrix, but at the expense of requiring type checking of the return value at the call site.  It also works for cases like multiplying two non-square matrices that happen to give a square result.  You give up most compile-time type checking, though.

If your application happens to mostly require run-time instead of compile-time type checking anyway, you might as well just give up the different types and throw an exception if you call a method that a non-square matrix doesn't support.  I believe this is the approach most existing libraries take, especially since there are other conditions than being non-square that can cause methods like inverse() to fail.

Speaking of libraries, there are a lot of good ones out there for matrix math, that are already heavily tested and optimized.  Don't reinvent the wheel if you don't have to.


问:
Designing Nested List<Class> Property in a Class
I'm currently in the class modeling phase of my project.

Real life Scenario:
Let's say I have a Project that is composed of Main Components and each Main Component is composed of Sub Components and each of Sub Components use multiple Materials.

I created a class based on the entities:

```<code>public class Project
{
    public List<MainComponent> MainComponents {get; set;}
    // other properties..
}

public class MainComponent
{
    public List<SubComponent> SubComponents {get;set;}
    //other properties..
}

public class SubComponents
{
    public List<Material> Materials {get;set;}
    //other properties..
}

public class Material
{
    //properties..
}
</code>```

However I will be having a hard time accessing a Material because I will have to go through a nested foreach loop

Let's say projectAlpha is an existing Instance of a Project class

```<code>foreach(MainComponent mainComponent in projectAlpha.MainComponents)
{
    foreach(SubComponent subComponent in mainComponent)
    {
        foreach(Material material in subComponent.Materials)
        {
            //do something with material here..
        }
    }
}
</code>```

What are efficient ways of designing a class that are based on entities that are designed like this? (Avoiding nested loops).

答:
You could maintain a hash map keyed by material id.

Each entry could be a linked list of the mainComponent and subComponent using the material
and perhaps a reference to the material object itself.

I should add that you should be careful to delete the index entry if you delete the "material" object. Garbage collection will not delete any object that has a valid reference.


答:
I don't think you design is bad or needs replacement. What you have is similar to the Component Pattern. Though, you might consider introducing some of the generalizations from the pattern (depending on your actual use case!).

If accessing all materials from a project is a common usage pattern of a project, rather than implementing the nested loops in each and every place, you should make material retrieval an operation on Project, like Project.AllMaterials. This could be implemented using one loop and delegation to MainComponent.AllMaterials, which, in turn, is implemented by one loop and delegation to SubComponent.Materials. The nested loops are then distributed over the classes and no client needs to care about their internal data structures. Most important, you don't need to reimplement these loops ever again!

Hope this helps!

Title: Designing Nested List<Class> Property in a Class

Body:
I'm currently in the class modeling phase of my project.

Real life Scenario:
Let's say I have a Project that is composed of Main Components and each Main Component is composed of Sub Components and each of Sub Components use multiple Materials.

I created a class based on the entities:

```<code>public class Project
{
    public List<MainComponent> MainComponents {get; set;}
    // other properties..
}

public class MainComponent
{
    public List<SubComponent> SubComponents {get;set;}
    //other properties..
}

public class SubComponents
{
    public List<Material> Materials {get;set;}
    //other properties..
}

public class Material
{
    //properties..
}
</code>```

However I will be having a hard time accessing a Material because I will have to go through a nested foreach loop

Let's say projectAlpha is an existing Instance of a Project class

```<code>foreach(MainComponent mainComponent in projectAlpha.MainComponents)
{
    foreach(SubComponent subComponent in mainComponent)
    {
        foreach(Material material in subComponent.Materials)
        {
            //do something with material here..
        }
    }
}
</code>```

What are efficient ways of designing a class that are based on entities that are designed like this? (Avoiding nested loops).


答:
The problem is that the concept of "this type" is missing in C#.  It can be simulated but it uses a syntax a bit complex or confusing, and I would not advise using it.  The question below describes such an implementation.

https://stackoverflow.com/questions/1400831/is-it-possible-to-make-this-type-for-generics-in-c

Title: Having an inherited function return the derived type instead of the base type

Body:
I am writing two classes in C#:

A Matrix class that represents a general Matrix with n-by-m dimensions

A SquareMatrix class that inherits from Matrix and has the constraint of being n-by-n

The reason I designed it this way is because square matrices support additional specific operations like calculating the determinant or the inverse, so being able to guarantee that those functions are avaliable with the specific type you're using are nice things to have. Additionally it would support all the regular Matrix operations and can be used as a Matrix

I have a function in Matrix called getTranspose(). It calculates the transpose of the Matrix and returns it as a new Matrix

I inherited it in SquareMatrix, but because the transpose of a square matrix is guaranteed to be square matrix, I also want it to return a SquareMatrix

I am unsure about the best way to do this.

I can re-implement the function in SquareMatrix, but that would be code duplication because it's essentially the same calculation

I can use implicit typecast operators, but if I understand correctly that would cause unnecessary allocations (upcast SquareMatrix to Matrix, create a new Matrix as the transpose, create a new SquareMatrix during typecasting and throw away the tranposed Matrix)

I can use explicit typecast operators, but it would be stupid to have to typecast the transpose of a SquareMatrix explicitly, and it also has the same problem of the implicit operator with unnecessary allocations

Is there another option? Should I change the design of having SquareMatrix inherit from Matrix?

This problem also applies to operators. It seems that I have to either implement typecasting operators which might cost in performance, or have to re-implement the same code.


问:
Database Context and Singleton injection with IoC
All of the below relates to a ASP.NET c# app.
I have a Singleton Settings MemoryCache that reads values from database on first access and caches these, then invalidates them using SQL Service Broker message and re-reads as required.

For the purposes of standard controllers, i create my Db Context in a request scope.
However, this obviously means that i can't use the same context in the Settings Cache class, since that is a singleton and we have a scope collision.

At the moment, i ended up with two db contexts - the Controllers get it via IoC container, whereas a Singleton just creates it's own.

However, i am not satisfied with this approach (mostly due to the way i feel about two contexts, the cache doesn't set anything on the db hence concurrency is not an issue as much).

What is a better way to do it?

答:
You could split your cache implementation into 2 parts, a Cache and a CacheStorage.

The CacheStorage is only responsible for storing the cached data, and has a Singleton
lifetime. Because it may be accessed by multiple threads concurrently, it should
be thread-safe.

The Cache is the dynamic part of the caching mechanism, it has a PerRequest
lifecycle and depends on both the CacheStorage and the DbContext.
It is responsible for reading the settings from the DbContext on first access and
updating the CacheStorage's data with it.

This way, the CacheStorage can be kept on for the duration of the application, and
the Cache gets instantiated only when there's a valid DbContext available.


问:
Is creating and writing to one large file faster than creating and writing to many smaller files in Python on Linux?
If using Python on a Linux machine, which of the following would be faster? Why?

Creating a file at the very beginning of the program, writing very large amounts of data (text), closing it, then splitting the large file up into many smaller files at the very end of the program.

Throughout the program's span, many smaller files will be created, written to and closed.

Specifically, the program in question is one which needs to record the state of a very large array at each of many time-steps. The state of the array at each time-step needs to be recorded in independent files.

I've worked with C on Linux and know that opening/creating and closing files is quite time-expensive, and fewer open/create operations means faster programs. Is the same true if writing in Python? Would changing the language even matter if still using the same OS?

I'm also interested in RAM's role in this context. For example -- correct me if I'm wrong -- I'm assuming that parts of a file being written to will be placed in RAM. If the file gets too big, will it bloat RAM and cause problems in speed or other areas? If an answer could incorporate RAM that would be great.

答:
I think it doesn't so much depend on the programming language, but on how Linux (and other systems) handle files: For each file that's created, an inode is created that contains meta information about the file. Therefore it is faster creating one large file than a myriad of smaller ones.

Regarding RAM, the OS should take care of it anyway. If too many pages get occupied, the OS writes them to the hard drive. If you want to handle it on your own, there's a flush function in python as well: http://www.tutorialspoint.com/python/file_flush.htm


答:
To answer your question, you really should benchmark (i.e. measure the execution time of several variants of your program). I guess it might depend on how many small files you need (10 thousand files is not the same as 10 billion files), and what file system you are using. You could use tmpfs file systems. It also obviously depends on the hardware (SSD disks are faster).

I would also suggest to avoid putting a big lot of files in the same directory. So prefer dir01/file001.txt ... dir01/file999.txt dir02/file001.txt ... to file00001.txt ... file99999.txt ie have directories with e.g. at most a thousand files.

I would also advise to avoid having a big lot of tiny files (e.g. files with less than a hundred bytes of data each): they make a lot of filesystems unhappy (since a file needs at least its inode).

However, you should perhaps consider other alternatives, like using a database (which might be as simple as Sqlite ...) or using some indexed file (like gdbm ...)

Regarding RAM, the kernel tries quite hard to keep file data in RAM. See e.g. linuxatemyram.com; read about posix_fadvise(2), fsync(2), readahead(2), ...

BTW, Python code will ultimately call C code and use the same (kernel provided) syscalls(2). Most file system related processing happens inside the Linux kernel. So it won't be faster (unless Python adds it own user-space buffering to e.g. read(2) data in megabyte chunks, hence lowering the number of executed syscalls).

Notice that every Linux system is able to deal with a lot of disk data, either with a single huge file (much bigger than available RAM: you could have a 50Gbyte file on your laptop, and a terabyte file on your desktop!) or in many files.

Title: Is creating and writing to one large file faster than creating and writing to many smaller files in Python on Linux?

Body:
If using Python on a Linux machine, which of the following would be faster? Why?

Creating a file at the very beginning of the program, writing very large amounts of data (text), closing it, then splitting the large file up into many smaller files at the very end of the program.

Throughout the program's span, many smaller files will be created, written to and closed.

Specifically, the program in question is one which needs to record the state of a very large array at each of many time-steps. The state of the array at each time-step needs to be recorded in independent files.

I've worked with C on Linux and know that opening/creating and closing files is quite time-expensive, and fewer open/create operations means faster programs. Is the same true if writing in Python? Would changing the language even matter if still using the same OS?

I'm also interested in RAM's role in this context. For example -- correct me if I'm wrong -- I'm assuming that parts of a file being written to will be placed in RAM. If the file gets too big, will it bloat RAM and cause problems in speed or other areas? If an answer could incorporate RAM that would be great.


问:
How can a new programmer impress the software engineer (boss)?
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.

答: Solve Rubik's cube. The boss will know that you like challenging puzzles and will give you tough assignments. </p>


问:
Addressing the fact that primary keys are not part of your business domain
In almost all circumstances, primary keys are not a part of your business domain. Sure, you may have some important user-facing objects with unique indices (UserName for users or OrderNumber for orders) but in most cases, there is no business need to overtly identify domain objects by a single value or set of values, to anyone  but perhaps an administrative user. Even in those exceptional cases, especially if you are using global unique identifiers (GUID), you will like or want to employ an alternate key rather than expose the primary key itself.

So, if my understanding of domain-driven design is accurate, primary keys need not and thus should not be exposed, and good riddance. They're ugly and cramp my style. But if we choose not to include primary keys in the domain model, there are consequences:

Naively, data transfer objects (DTO) that derive exclusively from combinations of domain models will not have primary keys

Incoming DTO's will not have a primary key

So, is it safe to say that if you are really going to stay pure and eliminate primary keys in your domain model, you should be prepared to be able to handle every request in terms of unique indices on that primary key?

Put in another way, which of the following solutions is the correct approach to dealing with identifying particular objects after removing PK in domain models?

Being able to identify the objects you need to deal with by other attributes

Getting the primary key back in the DTO; ie, eliminating the PK when mapping from persistence to domain, then recombining the PK when mapping from domain to DTO?

EDIT: Let's make this concrete.

Say my domain model is VoIPProvider which includes fields like Name, Description, URL, as well as references like ProviderType, PhysicalAddress, and Transactions.

Now let's say I want to build a web service that will allow privileged users to manage VoIPProviders.

Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons. So it may be enough to say that a unique VoIPProvider is completely determined by (Name, URL). So now let's say I need a method PUT api/providers/voip so that privileged users can update VoIP providers. They send up a VoIPProviderDTO, which includes many but not all of the fields from the VoIPProvider, including some flattening potentially. However, I can't read their minds, and they still need to tell me which provider we are talking about.

It seems I have 2 (maybe 3) options:

Include a primary key or alternate key in my domain model and send it to the DTO, and vice versa

Identify the provider we care about via the unique index, like (Name, Url)

Introduce some sort of intermediate object that can always map between persistence layer, domain, and DTO in a way that does not expose implementation details about the persistence layer - say by introducing an in-memory temporary identifier when going from domain to DTO and back,

答:
You need to be able to identify many objects by some unique index, and isn't that what a primary key is (or at least implies one is present).

Unique indexes are available so you can further constrain your DB schema, not as a wholesale replacement for PKs. If you're not exposing PKs becuase they;re ugly, but are exposing an unique key instead... you're not actually doing anything different. (I assume you're not getting a PK and an identity column mixed up here?)


答:
Without primary keys in the frontend there is no easy way for the backend to know what you are sending. To fix that you would need a ton of extra work parsing the data, which would hurt performance and probably take more time and be more ugly than attaching a key to every item.

As an example, lets say that I want to edit a message in an app; how would the app know which message I want to edit without a primary key attached? Editing objects happens all the time and doing that without keys is nigh impossible. But if you have objects that aren't supposed to be edited then skip the key if you think that it is distracting, but having primary keys can improve performance here.

Title: Addressing the fact that primary keys are not part of your business domain

Body:
In almost all circumstances, primary keys are not a part of your business domain. Sure, you may have some important user-facing objects with unique indices (UserName for users or OrderNumber for orders) but in most cases, there is no business need to overtly identify domain objects by a single value or set of values, to anyone  but perhaps an administrative user. Even in those exceptional cases, especially if you are using global unique identifiers (GUID), you will like or want to employ an alternate key rather than expose the primary key itself.

So, if my understanding of domain-driven design is accurate, primary keys need not and thus should not be exposed, and good riddance. They're ugly and cramp my style. But if we choose not to include primary keys in the domain model, there are consequences:

Naively, data transfer objects (DTO) that derive exclusively from combinations of domain models will not have primary keys

Incoming DTO's will not have a primary key

So, is it safe to say that if you are really going to stay pure and eliminate primary keys in your domain model, you should be prepared to be able to handle every request in terms of unique indices on that primary key?

Put in another way, which of the following solutions is the correct approach to dealing with identifying particular objects after removing PK in domain models?

Being able to identify the objects you need to deal with by other attributes

Getting the primary key back in the DTO; ie, eliminating the PK when mapping from persistence to domain, then recombining the PK when mapping from domain to DTO?

EDIT: Let's make this concrete.

Say my domain model is VoIPProvider which includes fields like Name, Description, URL, as well as references like ProviderType, PhysicalAddress, and Transactions.

Now let's say I want to build a web service that will allow privileged users to manage VoIPProviders.

Perhaps a user-friendly ID is useless in this case; after all, VoIP providers are companies whose names tend to be distinct in the computer sense and even distinct enough in the human sense for business reasons. So it may be enough to say that a unique VoIPProvider is completely determined by (Name, URL). So now let's say I need a method PUT api/providers/voip so that privileged users can update VoIP providers. They send up a VoIPProviderDTO, which includes many but not all of the fields from the VoIPProvider, including some flattening potentially. However, I can't read their minds, and they still need to tell me which provider we are talking about.

It seems I have 2 (maybe 3) options:

Include a primary key or alternate key in my domain model and send it to the DTO, and vice versa

Identify the provider we care about via the unique index, like (Name, Url)

Introduce some sort of intermediate object that can always map between persistence layer, domain, and DTO in a way that does not expose implementation details about the persistence layer - say by introducing an in-memory temporary identifier when going from domain to DTO and back,


答:
This is the way how we solve this (since more than 15 years, when even the term "domain driven design" was not invented):

when mapping the domain model to a database implementation or a class model in a specific programming language, you have a simple, consistent rule like "for each domain object mapped to a relational table, the primary key is "TablenameID".

this primary key is completely artificial, it has always the same type, and no business meaning - just a surrogate key

the "graphical version" of your domain model (the one you use to talk to your domain experts) does not contain primary keys. You don't expose them directly to the experts (but you expose them to anyone who is actually implementing code for the system).

So whenever you need a primary key for technical purposes (like mapping relations to a database), you have one available, but as long as you don't want to "see it", change your level of abstraction to the "domain experts model". And you don't have to maintain "two models" (one with PKs and one without); instead, maintain only a model without PKs and use a code generator to create the DDL for your DB, which adds the PK automatically according to the mapping rules.

Note that this does not forbid to add any "business keys" like an additional "OrderNumber", besides the surrogate OrderID. Technically these business keys become alternate keys when mapping to your database. Just avoid using these for creating references to other tables, always prefer using the surrogate keys if possible, this will make things a hell lot easier.

To your comment: using a surrogate key for identifying records is no business-related operation, it is a purely technical operation. To make this clear, look at your example: as long as you don't define additional unique-contraints, it would be possible to have two VoIPProvider objects with the same combination of (name,url), but different VoIPProviderIDs.


问:
How does Twitter's "dogfooding" work? If they are using different URL's, how are they using their own API?
I heard that twitter practices "dogfooding," meaning that they use their own API for the website. However, I don't really understand how that's true. When I use Firebug, I see that all the AJAX calls are made to some URL like:

```<code>https://twitter.com/{username}/{whatever else}
</code>```

Rather than:

```<code>https://api.twitter.com/1.1/statuses/...
</code>```

If they are using different URL's, how are they using their own API? I think I have the wrong notion of what an API is... Also, how would it work with OAuth? Do they validate themselves?

答: Twitter is definitely able to configure their web servers so that some HTTP requests are going (thru a "private route") to their "API".</p>


答:
The pragmatic answer is that if it works for your application and meets your current requirements then you're not doing it wrong :) However if you mean "is this a scalable, efficient, reusable solution" then the answer is no. The design makes many assumptions about how the threads will behave which may or may not be true in different situations (longer melodies, more simultaneous notes, different hardware, etc.).

As an alternative consider using a timing loop and a thread pool. The timing loop runs in it's own thread and continually checks if a note needs to be played. It does this by comparing the system time against the time that the melody was started. The timing of each note can normally be calculated very easily from the tempo of the melody and the sequence of notes. As a new note needs to be played, borrow a thread from a thread pool and call the play() function on the note. The timing loop can work in various ways but the simplest is a continuous loop with short sleeps (probably between chords) to minimise CPU usage.

An advantage of this design is that the number of threads will not exceed be the maximum number of simultaneous notes + 1 (the timing loop). Also the timing loop protects you against slippages in timings which could be caused by thread latency. Thirdly the tempo of the melody is not fixed and can be changed by altering the calculation of the timings.

As an aside, I agree with other commenters that the function note.play() is a very poor API to work with. Any reasonable sound API would allow you to mix and schedule notes in a much more flexible way. That said, sometimes we have to live with what we've got :)

Title: Multithreading: am I doing it wrong?

Body:
I'm working on an application that plays music.

During playback, often things need to happen on separate threads because they need to happen simultaneously. For example, the notes of a chord need to be heard together, so each one is assigned its own thread to be played in. (Edit to clarify: calling note.play() freezes the thread until the note is done playing, and this is why I need three separate threads to have three notes heard at the same time.)

This kind of behavior creates many threads during playback of a piece of music.

For example, consider a piece of music with a short melody and short accompanying chord progression. The entire melody can be played on a single thread, but the progression needs three threads to play, since each of its chords contains three notes.

So the pseudo-code for playing a progression looks like this:

```<code>void playProgression(Progression prog){
    for(Chord chord : prog)
        for(Note note : chord)
            runOnNewThread( func(){ note.play(); } );
}
</code>```

So assuming the progression has 4 chords, and we play it twice, than we are opening 3 notes * 4 chords * 2 times = 24 threads. And this is just for playing it once.

Actually, it works fine in practice. I don't notice any noticeable latency, or bugs resulting from this.

But I wanted to ask if this is correct practice, or if I'm doing something fundamentally wrong. Is it reasonable to create so many threads each time the user pushes a button? If not, how can I do it differently?


答:
Looks fine to me as a simple implementation, assuming that is the API you have to use. Other answers cover why this isn't a very good API, so I'm not talking about that more, I just assume it is what you have to live with. Your approach will use a large number of threads, but on a modern PC that should be no concern, as long as thread count is in the dozens.

One thing you should do, if feasible (like, playing from a file instead of from user hitting the keyboard), is to add some latency. So you start a thread, it sleeps until specific time of system clock, and starts to play a note at the right time (note, sometimes sleep may be interrupted early, so check clock and sleep more if needed). While there is no guarantee that OS will continue the thread exactly when your sleep ends (unless you use a real-time operating system), it's very likely to be much more accurate than if you just start the thread and start playing without checking the timing.

Then next step, which complicates things a bit but not too much, and will allow you to reduce the above mentioned latency is, use a thread pool. That is, when a thread finishes a note, it doesn't exit, but instead waits for a new note to play. And when you request starting to play a note, you first try to take a free thread from the pool, and add a new thread only if needed. This will require some simple inter-thread communication, of course, instead of your current fire-and-forget approach.

Title: Multithreading: am I doing it wrong?


问:
Which programming idiom to choose for this open source library?
Which programming idiom is easier to use for beginner developers writing concrete file parsing classes?

I'm developing an open source library, which one of the main functionality is to parse plain text files and get structured information from them. All of the files contain the same kind of information, but can be in different formats like XML, plain text (each of them is structured differently), etc. There are a common set of information pieces which is the same in all (e.g. player names, table names, some id numbers)

There are formats which are very similar to each other, so it's possible to define a common Base class for them to facilitate concrete format parser implementations. So I can clearly define base classes like SplittablePlainTextFormat, XMLFormat, SeparateSummaryFormat, etc. Each of them hints the kind of structure they aim to parse. All of the concrete classes should have the same information pieces, no matter what.

To be useful at all, this library needs to define at least 30-40 of these parsers. A couple of them are more important than others (obviously the more popular formats).

Now my question is, which is the best programming idiom to choose to facilitate the development of these  concrete classes? Let me explain:

I think imperative programming is easy to follow even for beginners, because the flow is fixed, the statements just come one after another. Right now, I have this:

```<code>class SplittableBaseFormat:
    def parse(self):
        "Parses the body of the hand history, but first parse header if not yet parsed."
        if not self.header_parsed:
            self.parse_header()

        self._parse_table()
        self._parse_players()
        self._parse_button()
        self._parse_hero()
        self._parse_preflop()
        self._parse_street('flop')
        self._parse_street('turn')
        self._parse_street('river')
        self._parse_showdown()
        self._parse_pot()
        self._parse_board()
        self._parse_winners()
        self._parse_extra()

        self.parsed = True
</code>```

So the concrete parser need to define these methods in order in any way they want. Easy to follow, but takes longer to implement each individual concrete parser.

So what about declarative? In this case Base classes (like SplittableFormat and XMLFormat) would do the heavy lifting based on regex and line/node number declarations in the concrete class, and concrete classes have no code at all, just line numbers and regexes, maybe other kind of rules.

Like this:

```<code>class SplittableFormat:
    def parse_table():
        "Parses TABLE_REGEX and get information"
        # set attributes here

    def parse_players():
        "parses PLAYER_REGEX and get information"
        # set attributes here

class SpecificFormat1(SplittableFormat):
    TABLE_REGEX = re.compile('^(?P<table_name>.*) other info \d* etc')
    TABLE_LINE = 1
    PLAYER_REGEX = re.compile('^Player \d: (?P<player_name>.*) has (.*) in chips.')
    PLAYER_LINE = 16

class SpecificFormat2(SplittableFormat):
    TABLE_REGEX = re.compile(r'^Tournament #(\d*) (?P<table_name>.*) other info2 \d* etc')
    TABLE_LINE = 2
    PLAYER_REGEX = re.compile(r'^Seat \d: (?P<player_name>.*) has a stack of (\d*)')
    PLAYER_LINE = 14
</code>```

So if I want to make it possible for non-developers to write these classes the way to go seems to be the declarative way, however, I'm almost certain I can't eliminate the declarations of regexes, which clearly needs (senior :D) programmers, so should I care about this at all? Do you think it matters to choose one over another or doesn't matter at all? Maybe if somebody wants to work on this project, they will, if not, no matter which idiom I choose. Can I "convert" non-programmers to help developing these? What are your observations?

Other considerations:
Imperative will allow any kind of work; there is a simple flow, which they can follow but inside that, they can do whatever they want.
It would be harder to force a common interface with imperative because of this arbitrary implementations.
Declarative will be much more rigid, which is a bad thing, because formats might change over time without any notice.
Declarative will be harder for me to develop and takes longer time. Imperative is already ready to release.

I'm looking for answers about which idioms to use when, which is better for open source projects with different scenarios, which is better for wide range of developer skills.

TL; DR:

Parsing different file formats (plain text, XML)

They contains same kind of information

Target audience: non-developers, beginners

Regex probably cannot be avoided

30-40 concrete parser classes needed

Facilitate coding these concrete classes

Which idiom is better?

答:
I think you can go the declarative minilanguage route, but you're unlikely to find one that works for all those formats.

Consider grouping your formats. For example:

for parsing XML, or anything similarly structured, using anything other than an XML parser is probably asking for trouble. You might be able to provide a general XML-to-whatever engine that less technical users can configure, maybe by just specifying which tags they want mapped to which fields.

for parsing text, full regular expressions look like overkill for your examples - you could handle those with scanf. You could probably provide a translation from something like Python format strings to regex, while still exposing REs directly to users who want them

eg. convert the slightly more user-friendly

```<code>'Player {player_num:d}: {player_name:s} has {player_chips:d} in chips.'
</code>```

to

```<code>'Player (?P<player_num>\d+): (?P<player_name>\S+) has (?<player_chips>\d+) in chips.'
</code>```

NB. the original string isn't much simpler than the RE, although there's a bit less noise, but there are many fewer opportunities for a non-technical user to confuse themselves than with an RE

for parsing CSV, fixed-width or binary formats, some general parser can probably be configured with delimiter, field width, or type+size info respectively. Then we're back to specifying the mapping from columns to fields, similar to the XML.

Since none of these have anything much in common, trying to fit them all into a single DSL is hard. It'll end up -like regular expressions - being too general for a beginner to learn easily.

The downside is, it will be hard to provide any uniformity or consistency between formats in different groups. Still, each individual group should be much easier to learn and support.

Body:
I think you can go the declarative minilanguage route, but you're unlikely to find one that works for all those formats.

Consider grouping your formats. For example:

for parsing XML, or anything similarly structured, using anything other than an XML parser is probably asking for trouble. You might be able to provide a general XML-to-whatever engine that less technical users can configure, maybe by just specifying which tags they want mapped to which fields.

for parsing text, full regular expressions look like overkill for your examples - you could handle those with scanf. You could probably provide a translation from something like Python format strings to regex, while still exposing REs directly to users who want them

eg. convert the slightly more user-friendly

'Player {player_num:d}: {player_name:s} has {player_chips:d} in chips.'

to

'Player (?P<player_num>\d+): (?P<player_name>\S+) has (?<player_chips>\d+) in chips.'

NB. the original string isn't much simpler than the RE, although there's a bit less noise, but there are many fewer opportunities for a non-technical user to confuse themselves than with an RE

for parsing CSV, fixed-width or binary formats, some general parser can probably be configured with delimiter, field width, or type+size info respectively. Then we're back to specifying the mapping from columns to fields, similar to the XML.

Since none of these have anything much in common, trying to fit them all into a single DSL is hard. It'll end up -like regular expressions - being too general for a beginner to learn easily.

The downside is, it will be hard to provide any uniformity or consistency between formats in different groups. Still, each individual group should be much easier to learn and support.


问:
In which stage of compilation is "typedef" resolved by the compiler?
There are different stages of compilation

Such as

Preprocessing stage

Syntax analysis

Semantic analysis

Intermediate Code generation

Machine Code generation

Optimization

Linking

My question here is in which stage of compilation "typedef" is resolved.

答:
The meaning of typedef is defined in the standard at n1256 S6.7.7. It says:

A typedef declaration does not introduce a new type, only a
  synonym for the type so specified.

In other words, a typedef is complete and meaningful as soon as the declaration is complete. Nothing is left to be analysed later.

Although giving things meanings is part of semantic analysis, this particular action must take place during syntactic analysis, because this information is used later to choose between possibly ambiguous syntactic interpretations. For example S6.7.3:

If the same qualifier appears more than once in the same specifier-qualifier-list, either
  directly or via one or more typedefs, the behavior is the same as if it appeared only
  once.

So the answer is: during syntax analysis, with the reservation that this might be taken to overlap with semantic analysis.


问:
Is it a good practice to declare instance variables as None in a class in Python?
Consider the following class:

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

My coworkers tend to define it like this:

```<code>class Person:
    name = None
    age = None

    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

The main reason for this is that their IDE of choice shows the properties for autocompletion.

Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None.

Which one would be better practice and for what reasons?

答:
Personally I define the members in the __ init__() method. I never thought about defining them in the class part. But what I always do: I init all of the members in the __ init__ method, even those not needed in the __ init__ method.

Example:

```<code>class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age
        self._selected = None

   def setSelected(self, value):
        self._selected = value
</code>```

I think it is important to define all members in one place. It makes the code more readable. Whether it is inside __ init__() or outside, is not that important. But it is important for a team to commit to more or less the same coding style.

Oh, and you may notice I ever add the prefix "_" to member variables.

ContentLicense: CC BY-SA 4.0

Body:
Personally I define the members in the __ init__() method. I never thought about defining them in the class part. But what I always do: I init all of the members in the __ init__ method, even those not needed in the __ init__ method.

Example:

class Person:
    def __init__(self, name, age):
        self._name = name
        self._age = age
        self._selected = None

   def setSelected(self, value):
        self._selected = value

I think it is important to define all members in one place. It makes the code more readable. Whether it is inside __ init__() or outside, is not that important. But it is important for a team to commit to more or less the same coding style.

Oh, and you may notice I ever add the prefix "_" to member variables.


答:
You should look into parser combinator libraries, which when set up properly, can give you declarative syntax that's easier to read than either your recursive descent example or your regex example.  Done correctly, it sort of looks like concatenating a string, but it works in reverse.  With some work on your part, it might look something like:

```<code>parser = "Player" + playerNumber + ":" + playerName + "has" + chipCount + "in chips"
</code>```

That being said, if you truly want non-programmers to contribute, you're going to want to create some sort of guided graphical extractor.  Think of the wizard you get when you open a text file in Excel, or the way AdBlock lets you choose an element on the page to block.  The code does some autodetect on the basic structure, the user answers some questions to get the columns looking right, labels the different fields, then the code highlights all the fields and the user confirms.  This system would be difficult to create, but will make maintenance of changes to the formats very nice.

Title: Which programming idiom to choose for this open source library?

Body:
Which programming idiom is easier to use for beginner developers writing concrete file parsing classes?

I'm developing an open source library, which one of the main functionality is to parse plain text files and get structured information from them. All of the files contain the same kind of information, but can be in different formats like XML, plain text (each of them is structured differently), etc. There are a common set of information pieces which is the same in all (e.g. player names, table names, some id numbers)

There are formats which are very similar to each other, so it's possible to define a common Base class for them to facilitate concrete format parser implementations. So I can clearly define base classes like SplittablePlainTextFormat, XMLFormat, SeparateSummaryFormat, etc. Each of them hints the kind of structure they aim to parse. All of the concrete classes should have the same information pieces, no matter what.

To be useful at all, this library needs to define at least 30-40 of these parsers. A couple of them are more important than others (obviously the more popular formats).

Now my question is, which is the best programming idiom to choose to facilitate the development of these  concrete classes? Let me explain:

I think imperative programming is easy to follow even for beginners, because the flow is fixed, the statements just come one after another. Right now, I have this:

```<code>class SplittableBaseFormat:
    def parse(self):
        "Parses the body of the hand history, but first parse header if not yet parsed."
        if not self.header_parsed:
            self.parse_header()

        self._parse_table()
        self._parse_players()
        self._parse_button()
        self._parse_hero()
        self._parse_preflop()
        self._parse_street('flop')
        self._parse_street('turn')
        self._parse_street('river')
        self._parse_showdown()
        self._parse_pot()
        self._parse_board()
        self._parse_winners()
        self._parse_extra()

        self.parsed = True
</code>```

So the concrete parser need to define these methods in order in any way they want. Easy to follow, but takes longer to implement each individual concrete parser.

So what about declarative? In this case Base classes (like SplittableFormat and XMLFormat) would do the heavy lifting based on regex and line/node number declarations in the concrete class, and concrete classes have no code at all, just line numbers and regexes, maybe other kind of rules.

Like this:

```<code>class SplittableFormat:
    def parse_table():
        "Parses TABLE_REGEX and get information"
        # set attributes here

    def parse_players():
        "parses PLAYER_REGEX and get information"
        # set attributes here

class SpecificFormat1(SplittableFormat):
    TABLE_REGEX = re.compile('^(?P<table_name>.*) other info \d* etc')
    TABLE_LINE = 1
    PLAYER_REGEX = re.compile('^Player \d: (?P<player_name>.*) has (.*) in chips.')
    PLAYER_LINE = 16

class SpecificFormat2(SplittableFormat):
    TABLE_REGEX = re.compile(r'^Tournament #(\d*) (?P<table_name>.*) other info2 \d* etc')
    TABLE_LINE = 2
    PLAYER_REGEX = re.compile(r'^Seat \d: (?P<player_name>.*) has a stack of (\d*)')
    PLAYER_LINE = 14
</code>```

So if I want to make it possible for non-developers to write these classes the way to go seems to be the declarative way, however, I'm almost certain I can't eliminate the declarations of regexes, which clearly needs (senior :D) programmers, so should I care about this at all? Do you think it matters to choose one over another or doesn't matter at all? Maybe if somebody wants to work on this project, they will, if not, no matter which idiom I choose. Can I "convert" non-programmers to help developing these? What are your observations?

Other considerations:
Imperative will allow any kind of work; there is a simple flow, which they can follow but inside that, they can do whatever they want.
It would be harder to force a common interface with imperative because of this arbitrary implementations.
Declarative will be much more rigid, which is a bad thing, because formats might change over time without any notice.
Declarative will be harder for me to develop and takes longer time. Imperative is already ready to release.

I'm looking for answers about which idioms to use when, which is better for open source projects with different scenarios, which is better for wide range of developer skills.

TL; DR:

Parsing different file formats (plain text, XML)

They contains same kind of information

Target audience: non-developers, beginners

Regex probably cannot be avoided

30-40 concrete parser classes needed

Facilitate coding these concrete classes

Which idiom is better?

Body:
You should look into parser combinator libraries, which when set up properly, can give you declarative syntax that's easier to read than either your recursive descent example or your regex example.  Done correctly, it sort of looks like concatenating a string, but it works in reverse.  With some work on your part, it might look something like:

parser = "Player" + playerNumber + ":" + playerName + "has" + chipCount + "in chips"

That being said, if you truly want non-programmers to contribute, you're going to want to create some sort of guided graphical extractor.  Think of the wizard you get when you open a text file in Excel, or the way AdBlock lets you choose an element on the page to block.  The code does some autodetect on the basic structure, the user answers some questions to get the columns looking right, labels the different fields, then the code highlights all the fields and the user confirms.  This system would be difficult to create, but will make maintenance of changes to the formats very nice.


答:
Did I ever tell you about Ashton?

Ashton was your classic corn-fed farm boy. His parents had been hippies who never really managed to get their acts together until his mother inherited 15 acres in a rural part of Michigan. The family moved out there, bought a couple of dairy goats, and struggled to make a living selling organic goat cheese to the yuppies at the Ann Arbor Farmer’s Market.

From the time he was ten years old, Ashton had to wake up every morning at 4:00 a.m. and milk those damn goats, and it was exhausting. Ashton loved going to school because it meant he wasn’t working knee-deep in goat poop. Throughout high school, he studied his ass off, hoping that a scholarship to a good university would be his ticket out of the farm. He found college to be so much easier than farm life that he didn’t understand why everyone else didn’t get straight A’s like him. He majored in Software Engineering because he couldn’t imagine engineers ever being required to wake up at 4:00 a.m.

Ashton graduated from school without knowing much about the software industry, really, so he went to the career fair, applied for three jobs, got accepted by all three, and picked the one that paid the most: something insane like $32,000 a year, working at a big furniture company in the southwestern part of the state that manufactured cubicle farms for corporations all over the world. He never wanted to see a farm again, so he was determined to make a good impression on his boss, Charlie Sherman.

“That’s not going to be easy,” his cubicle-mate, Jeff, said. “She’s something of a legend here.”

“What do you mean?” he asked.

“Well, you remember a few years ago, when there was all that uproar about Y2K?”

Ashton was probably too young. “Y2K?”

“You know, nobody expected that all the old computer programs written in the 1960s would still be running in 2000, so they only had room for two digits for the year. Instead of storing 1999, they would store 99. And then when the year flipped over on January 1st, 2000, the computer systems crashed, because they tried to fit “100” in two digits.

“Really? I thought that was a myth,” Ashton said.

“At every other company in the world, nothing happened,” Jeff said. “They spent billions of dollars checking every line of code. But here, of course, they’re cheap bastards, so they didn’t bother doing any testing.”

“Not at all?”

“Zilch. Zero testing. Nada. And lo and behold, when people staggered back into work on January 2nd, not a single thing worked. They couldn’t print production schedules. They couldn’t get half of the assembly lines to even turn on. And nobody knew what shifts they were supposed to be working. The factory literally came to a standstill.”

“You’re kidding,” Ashton said.

“I shit you not. The factory was totally silent. Now, Charlie, she was new then. She had been working at Microsoft, or NASA, or something... nobody could figure out why someone like her would be working in our little armpit of a company. But she sat down, and she started coding. And coding. And coding.

“Charlie coded for nine days straight. Nine days without sleeping, without eating, some people even claimed she never went to the bathroom. She went from system to system and literally fixed all of them. It was something to behold. My God, there were COBOL systems in there that needed to be fixed. The whole factory at a standstill, and Charlie is sending people to the university library in Ann Arbor to find old COBOL manuals. Assembly-line workers are standing around shivering, because even the thermostats had a Y2K bug. And Charlie is drinking cup after cup of coffee and typing like a madwoman.”

“Wow. And she never went to the bathroom?”

“Well, that part might be a little bit of an exaggeration. But she really did work 24 hours for nine days straight. Anyway, on January 11th, about five minutes before the day shift is supposed to start, she comes out of her cubicle, goes to the line printer, hits a button, and boom! out comes the production schedules, and the team schedules, and everything is perfect, perfectly formatted, using a slightly smaller font so that the “2000” fits where it used to say “99,” and she’s even written a new priority optimizing system that helps them catch up with 9 days of missed production without pissing off too many customers, and all the assembly lines start running like nothing was ever wrong, and the heat comes on, and the invoices come out printed with ‘2000’ as the year instead of ‘19100,’ and after that day, nobody found a single bug.”

“Oh come on!” Ashton says. “Nobody writes code without bugs.”

“She did. I saw it with my own eyes. The first day back they ran two days worth of cubicles without a hiccup.”

Ashton was dumbstruck. “That’s epic. How can I live up to that?”

“You can’t, buddy, nobody can,” Jeff said, turning back to his computer terminal, where he resumed an online flame war over who would win in a fight, Spock or Batman, which had been raging for over four months.

Not one to give up, Ashton swore he would, one day, do something legendary. But the truth is, there never was another Y2K. And nobody, in that part of Michigan, gave a rat’s ass about good programming. There was almost nothing for the programmers to do, in fact. Ashton got dumb little projects assigned to him... at one point he spent three weeks working on handling a case where the sales tax in one particular county was wrong because some zip code spanned two different sales tax zones. The funny thing was, it was in some unpopulated part of New York State where nobody ever bought office cubicles, and they had never had a customer there, so his code would never run.

Ever.

For two years Ashton came into work enthusiastic and excited, and dying to make a difference and do something terrific and awesome, while his coworkers surfed the Internet, sent instant messages to their friends, and played computer solitaire for hours.

Jeff, his cubicle-mate, only had one responsibility: updating the weekly Excel spreadsheet indicating how many people were hurt on the job that week. Nobody ever was. Once a week, Jeff opened the spreadsheet, went to the bottom of the page, entered the date and a zero, hit save, and that was that.

Ashton even wrote a macro for Jeff that automated that one task. Jeff didn’t want to get caught, so he refused to install it. They weren’t on speaking terms after that. It was awkward.

On the morning of his two year anniversary at the cubicle company, Ashton was driving to work when he realized something.

Not one line of code that he had written had ever run.

Not one thing he had done in two years of work made any impact on the world.

And it was fucking 24 degrees in that part of Michigan, and it was gray, and smelly, and his Honda was a piece of crap, and he didn’t have any friends in town, and nothing he did mattered.

As he drove down Lincoln Avenue, he saw the furniture company ahead on the left. Three flags fluttered in front of the corporate campus: an American flag, a flag of the great state of Michigan, and a white and red flag with the company logo. He got in the turning lane behind a long line of cars waiting to turn left. It always took four or five traffic light cycles, at rush hour, to make the turn, so Ashton had plenty of time to try to remember if any code he had ever written was ever used by anyone.

And it hadn’t. And he fought back a tear.

And instead of turning left, he went straight, almost causing an accident because he forgot that the left turn light didn’t mean you could go straight.

And he drove right down Lincoln Avenue,  and got onto the Gerald Ford freeway, and he just kept driving until he got to the airport over in Grand Rapids, and he left his crappy old Honda out right in front of the terminal, knowing perfectly well it would be towed, and didn’t even close the car door, and he walked right up to the Frontier Airlines counter and he bought himself a ticket on the very next flight to San Francisco, which was leaving in 20 minutes, and he got on the plane, and he left Michigan forever.

Title: How can a new programmer impress the software engineer (boss)?

Body:
I'm working at my first programming job. My boss is a very smart software engineer, and I feel
like I have very little to offer compared to him. Problem is, he is always busy, and needs someone to help him out. I feel like I'm not good enough, but I still want to succeed. I want to be a great programmer.

What can I do to impress him?

Thank you.


问:
Basic PHP Object Oriented Design Review
I am attempting to learn object oriented programming by designing a simple web application related to the Catholic liturgical calendar. I have very little formalized training in programming, but I have been able to more-or-less successfully learn basic programming concepts and the purposes/syntax of a couple languages.

I was hoping that I could receive feedback on the following design I have worked out and implemented in testing. The basic use case is to be able to find the calendar details of any date and time through both application logic and some database queries. I have developed the classes as such:

```<code>class Year
    create several DateTime objects for important movables feasts for a year

class Season extends Year
    create several properties for each liturgical season based on the DateTime
    objects from Year and additional application logic

class Day extends Season
    contains an array of Hours objects since a liturgical day is not necessarily
    the same as a 24 hour temporal day

class Hour extends Day
    determines the liturgical hour details including the feast being celebrated
    and DateTime objects representing the start and stop times of the hour since
    and "hour" <> a temporal hour of 60 minutes
</code>```

With this design, I can create an Hour by passing a single parameter ($date). The Hour needs to know which liturgical season it is for some application logic, so it creates a Season object based on $date. The Season object, however, cannot be created until it knows when certain important feast days occur in any given year (e.g. Easter determines the start and stop dates for several liturgical seasons), so it creates a Year object. Is this a "desirable" pattern such that to create a single desired object (Hour) two other objects (Season and Year) are created? Is it "proper" to extend classes to reflect a hierarchical relationship such as I have (i.e. the largest temporal period is "at top", followed by the largest subdivision of that, etc...down to the smallest temporal period of hour)?

The primary purpose of this web application will be to display religious facts and literature based on the current liturgical hour. Thus, the Hour is the most important piece to the end user - but this cannot be determined successfully without the "larger" periods of Season and Year. The Day object will be used for navigation/information purposes only (e.g. what are the important religious occurrences at all the liturgical hours today?) and will likely not include any actionable events within it.

In testing, I have created a year's worth of Date objects which results in 2,920 Hour, Season and Year objects (365 * 8 for each object type = 8,760 total objects). The application logic is correct and produces desired data results. However, this seems like an incredibly high number of object instantiations for such a simple system, so I would like to know if I am misusing objects or totally misunderstanding their purpose. I think it may be more desirable to be able to create a single Year object which would produce 13 Season objects that could then be referenced by each Hour that I need to create...thus creating only 2,934 objects (2,920 Hour, 13 Season and 1 Year).

Any thoughts would be appreciated!

答:
What I think @SlappyTheFish is getting at in his comment is that with extension you're basically telling your code that a Season IS a Year. When in reality, a Season IS NOT a year, a year HAS seasons. That's basically the reference to is-a and has-a that he had mentioned.

Now looking at encapsulation you would have:

1 year object

4 Season Objects, contained within a Seasons array inside Year.

Each Season object would contain an array of Day objects (The number to correspond to the correct distribution of days to Seasons)

Each day object would contain an Hours array, which would contain 24 Hours objects.

Whether or not this is the best design is a different question, but it gives you an idea of encapsulation instead of inheritance.

Title: Basic PHP Object Oriented Design Review


问:
Eliminate duplicate code in nested IFs without creating a function
Let's say we have two ifs that depend on each other:

```<code>if var exists {
    if var is array {
        //Do stuff with var
    } else {
        //Resolve the problem
    }
} else {
    //Resolve the problem in the exact same way as above
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

How can I refactor this to remove the duplicated code without using gotos or functions/methods?

答:
Assuming the tests cannot be joined in one expression I would write:</p>

```<code>bool ok = false;
if var exists {
    if var is array {
        //Do stuff with var
        ok = true;
    }
}
if (!ok) {
    //Resolve the problem
}
//Continue execution with the assumption that var is in the appropriate state
</code>```

Body:
Assuming the tests cannot be joined in one expression I would write:

bool ok = false;
if var exists {
    if var is array {
        //Do stuff with var
        ok = true;
    }
}
if (!ok) {
    //Resolve the problem
}
//Continue execution with the assumption that var is in the appropriate state


答:
The reason we use a non-business related PK is to ensure that our system has an easy and consistent method of determining what the user wants.

I see you replied with a comment: MessageSender, MessageRecipient, TimeSent (for a message). You can STILL have ambiguity this way (for example, with system generated messages triggering on something that happens often). And how are you going to validate MessageSender and MessageRecipient here? Suppose you validate them using FirstName, Lastname, DateOfBirth, you're going to eventually run into a situation where you have 2 people born on the same day with the exact same name. Not to mention that you will run into a situation where you have a message named tacostacostacos-America-1980-Doc Brown-France-1965-23/5/2014-11:43:54.003UTC+200. That's a monster of a name, and you still have no guarantee you'll only have 1 of those.

the reason we use a primary key is because we KNOW it'll be unique for the lifetime of the software, no matter what data is entered, and we KNOW it's going to be a predictable format (what happens if your above key has a dash in a username? your whole system goes to shit).

You don't need to show your ID to your user. You can hide that (in plain sight if necessary, through the URL).

Another reason why a PK is so useful is something you can deduce from the above: a PK makes it so that you don't have to force the computer to interpret user-generated code. If a Chinese user uses your code and enters a bunch of Chinese characters, your code suddenly doesn't need to be able to work with these internally, but it can simply use the Guid that the system generated. If you have an Arabic user who enters Arabic writing, your system doesn't have to cope with that internally, but can basically ignore that they're there.

As others have said, a Guid is something that can be stored internally in a fixed size. You know what you work with and it's something that can be universally used. You don't need to create design rules on how you create a certain identifier and save it. If your system only takes the first 10 letters of a name, it doesn't see any difference between Michael Guggenheimer and Michael Gugstein, and it will confuse these 2. If you cut it off at any arbitrary length, you can run into confusion. If you limit user input, you can run into issues with user limitations.

When I look at existing systems like Dynamics CRM, they also use the internal key (the PK) for the user to call upon a single record. If a user has a query that doesn't involve the ID, they return an array of possible answers and let the user choose from it. If there is any chance at ambiguity, they'll give the choice to the user.

Finally, it's also abit of security through obscurity. If you don't know the record ID, your only option is to guess it. if the ID is easy to guess (because the information that it's made of is publicly available), anyone can change it. You can even goad the user into changing it through classic CSRF or XSS methods. Now, obviously your security should already have those accounted for and mitigated before ever publishing the live version, but you should still make it harder for potential abuse to happen.


答:
This is a bad practice. You don't need those values, they clutter up the code, and they can cause errors.

Consider:

```<code>>>> class WithNone:
...   x = None
...   y = None
...   def __init__(self, x, y):
...     self.x = x
...     self.y = y
...
>>> class InitOnly:
...   def __init__(self, x, y):
...     self.x = x
...     self.y = y
...
>>> wn = WithNone(1,2)
>>> wn.x
1
>>> WithNone.x #Note that it returns none, no error
>>> io = InitOnly(1,2)
>>> InitOnly.x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class InitOnly has no attribute 'x'
</code>```

Title: Is it a good practice to declare instance variables as None in a class in Python?

Body:
Consider the following class:

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

My coworkers tend to define it like this:

```<code>class Person:
    name = None
    age = None

    def __init__(self, name, age):
        self.name = name
        self.age = age
</code>```

The main reason for this is that their IDE of choice shows the properties for autocompletion.

Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None.

Which one would be better practice and for what reasons?

Body:
This is a bad practice. You don't need those values, they clutter up the code, and they can cause errors.

Consider:

>>> class WithNone:
...   x = None
...   y = None
...   def __init__(self, x, y):
...     self.x = x
...     self.y = y
...
>>> class InitOnly:
...   def __init__(self, x, y):
...     self.x = x
...     self.y = y
...
>>> wn = WithNone(1,2)
>>> wn.x
1
>>> WithNone.x #Note that it returns none, no error
>>> io = InitOnly(1,2)
>>> InitOnly.x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class InitOnly has no attribute 'x'


答:
I call the latter bad practice under the "this does not do what you think it does" rule.

Your coworker's position can be rewritten as: "I am going to create a bunch of class-static quasi-global variables which are never accessed, but which do take up space in the various class's namespace tables (__dict__), just to make my IDE do something."


答:
1. Make your code easy to understand

Code is read much more often than written. Make your code maintainer's task easier (it as well may be yourself next year).

I don't know about any hard rules, but I prefer to have any future instance state clearly declared outright. Crashing with an AttributeError is bad enough. Not seeing clearly the lifecycle of an instance attribute is worse. The amount of mental gymnastic required to restore possible call sequences that lead to the attribute being assigned can easily become non-trivial, leading to errors.

So I usually not only define everything in constructor, but also strive to keep the number of mutable attributes to a minimum.

2. Don't mix class-level and instance-level members

Anything you define right inside the class declaration belongs to the class and is shared by all instances of the class. E.g. when you define a function inside a class, it becomes a method which is the same for all instances. Same applies to data members. This is totally unlike instance attributes you usually define in __init__.

Class-level data members are most useful as constants:

```<code>class Missile(object):
  MAX_SPEED = 100  # all missiles accelerate up to this speed
  ACCELERATION = 5  # rate of acceleration per game frame

  def move(self):
    self.speed += self.ACCELERATION
    if self.speed > self.MAX_SPEED:
      self.speed = self.MAX_SPEED
    # ...
</code>```

Body:
1. Make your code easy to understand

Code is read much more often than written. Make your code maintainer's task easier (it as well may be yourself next year).

I don't know about any hard rules, but I prefer to have any future instance state clearly declared outright. Crashing with an AttributeError is bad enough. Not seeing clearly the lifecycle of an instance attribute is worse. The amount of mental gymnastic required to restore possible call sequences that lead to the attribute being assigned can easily become non-trivial, leading to errors.

So I usually not only define everything in constructor, but also strive to keep the number of mutable attributes to a minimum.

2. Don't mix class-level and instance-level members

Anything you define right inside the class declaration belongs to the class and is shared by all instances of the class. E.g. when you define a function inside a class, it becomes a method which is the same for all instances. Same applies to data members. This is totally unlike instance attributes you usually define in __init__.

Class-level data members are most useful as constants:

class Missile(object):
  MAX_SPEED = 100  # all missiles accelerate up to this speed
  ACCELERATION = 5  # rate of acceleration per game frame

  def move(self):
    self.speed += self.ACCELERATION
    if self.speed > self.MAX_SPEED:
      self.speed = self.MAX_SPEED
    # ...