问:
OO Design, how to model Tonal Harmony?
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.

答:
I'm finding this dicussion fascinating.

Are the notes being input via midi (or some type of tone capture device) or are they being entered by typing the letters and symbols?

In the case of the interval from C to D-sharp/E-flat:

Although D-sharp and E-flat are the same tone (around 311Hz if A=440Hz), the interval from C -> D-sharp is written an augmented 2nd, while the interval from C -> E-flat is writtem as a minor 3rd.  Easy enough if you know how the note was written.  Impossible to determine if you only have the two tones to go on.

In this case, I believe you are also going to need a way to increment/decrement the tone along with the .Sharpen() and .Flatten() methods mentioned, such as .SemiToneUp() , .FullToneDown(), etc. so that you can find subesquent notes in a scale without "coloring" them as sharps/flats.

I have to agree with @Rotem that "C" is not a class in and of itself, but rather an instantiation of the Note class.

If you define the properties for a note, including all the intervals as semitones, then regardless of the initial note value ("C", "F", "G#") you would be able to tell that a three note sequence that has the root, major 3rd (M3), then minor 3rd(m3) would be a major triad.  Similarly, m3+M3 is a minor triad, m3+m3 diminished, M3+M3 augmented.
Additionally, this would give you a way to encapsulate finding the 11th, diminished 13th, etc. without explicitly coding them for all 12 base notes, and their octaves up and down.

Once that's done, you're still left with some problems to solve.

Take the triad C,E,G.  As a musician, I see this clearly as a Cmaj chord.
However, the developer in me can interpret this additionaly as E minor Augment 5 (Root E+m3+a5) or Gsus4 6th no 5th (RootG + 4 + 6).

So, to answer your question about doing the analysis, I think the best way to determine modality (maj, minor, etc) would be to take all the notes entered, arrange them in ascending semitone value, and test them against the known chord forms.  Then, use each note entered as the root note, and perform the same set of evaluations.

You could weight the chord forms so that more common (major, minor) have precedence over the augmented, suspended, elektra, etc. chord forms, but an accurate analysis would require presenting all matching chord forms as possible solutions.

Again the wikipedia article referenced does a good job of listing the pitch classes, so it should be simple (albeit tedious) to code up the models of the chords, the take the entered notes, assigne them to pitch classes/intervals, and then compare against the known forms for matches.

This has been a lot of fun.  Thanks!

Title: OO Design, how to model Tonal Harmony?


问:
Can I (reasonably) refuse to sign an NDA for pro bono work?
A friend of mine (let's call him Joe) is working on a promising project, and has asked me for help. As a matter of friendship I agreed (orally) not to discuss the details, but now he has a potential investor who wants me to sign a non-disclosure agreement (NDA). Since thus far all my work has been pro bono I told Joe I am not comfortable putting myself under documented legal obligation without some kind of compensation for the risk. (It needn't be strictly financial. I would accept a small ownership stake or possibly even just guaranteed credits in the code and documentation.)

Is my request reasonable, or am I just introducing unnecessary complexity?

答:
Recap: Your friend brought you in, and, as a friend, asked you not to talk about the project.  You agreed.  Your friend is now talking to an investor, which means that there are potentially Big Bucks involved.  The investor wants to bind and gag you, legally.

There is a basic concept in contract law known as "quid pro quo".  In everyday language, this may be translated as "What's in it for me?"  Whenever you are asked to sign some piece of legal paper, if the answer to that question is not BOTH immediately apparent AND to your basic liking, DON'T SIGN IT!

In this case, your "consideration" under the NDA, meaning "what's in it for you", does not appear to be well-defined.  As such, your reply to their request is eminently reasonable.

In the future, the easy out is "My attorney has strongly advised that I never sign anything without running it past him first, and he's never given me bad advice.  Let me go over this with him (or her) and get back to you."  Then watch their reaction.  If they have any problem at all with letting your attorney review their NDA, the old Monty Pyton line becomes applicable: "RUN AWAY! RUN AWAY!"

ContentLicense: CC BY-SA 3.0


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
Research Results

As an academic, I figured I should share what I optimize for. Note that this isn't quite the same as optimizing for a shorter development time. Often it means that the work might support some research question, but not be a deliverable, polished product. This might be viewed as an issue with quality, and it could explain why many say that (academic) computer scientists don't have any "real world" experience. (E.g., "Wouldn't they know how to develop a deliverable product otherwise?")

It's a fine line. In terms of impact, you want your work to be used and cited by others, and Joel's Iceberg Effect comes into play: a little polish and shine can go a long way. But if you aren't making a foundation for other projects to be built on, you just might not be able to justify the time spent making a deliverable product.

ContentLicense: CC BY-SA 2.5

Title: What do you optimize for?


问:
How do I express subtle relationships in my data?
"A" is related to "B" and "C". How do I show that "B" and "C" might, by this context, be related as well?

Example:

Here are a few headlines about a recent Broadway play:

David Mamet's Glengarry Glen Ross, Starring Al Pacino, Opens on Broadway

Al Pacino in 'Glengarry Glen Ross': What did the critics think?

Al Pacino earns lackluster reviews for Broadway turn

Theater Review: Glengarry Glen Ross Is Selling Its Stars Hard

Glengarry Glen Ross; Hey, Who Killed the Klieg Lights?

Problem:

Running a fuzzy-string match over these records will establish some relationships, but not others, even though a human reader could pick them out from context in much larger datasets.

How do I find the relationship that suggests #3 is related to #4? Both of them can be easily connected to #1, but not to each other.

Is there a (Googlable) name for this kind of data or structure? What kind of algorithm am I looking for?

Goal:

Given 1,000 headlines, a system that automatically suggests that these 5 items are all probably about the same thing.

To be honest, it's been so long since I've programmed I'm at a loss how to properly articulate this problem. (I don't know what I don't know, if that makes sense).

This is a personal project and I'm writing it in Python. Thanks in advance for any help, advice, and pointers!

答:
If at all possible, get the story along with the headline. Headlines can sometimes get "cute" and make only tangential reference to what is being discussed. This works OK with humans (because they have global context), but not so well with NLP.

As mentioned in Karl Bielefeldt's answer, clustering is a good approach, but the Devil is in the details. You not only have to pick a clustering approach that fits your problem/user space, you also have to figure out what is being clustered.

My background is in Information Retrieval (IR) from the 80's-90's, and we focused on similarity searching and centroid-based clustering. Our documents were represented by weighted attribute vectors, which is basically a list of terms and their relative importance in the doc. This approach can work (although better with some collections than others), but it has problems with short-cute headlines, because they lack key vocabulary terms to tie things together. But if you use the whole document, then you get a much richer list of terms (and probably a better sense of importance), and that list of terms will probably make the connection easier to spot (i.e. compute) when you have headlines that are "cute".

My email is in my profile if you would like to get into vector generation issues, etc.


问:
Inheritance from the objects themselves
Making new inheritance hierarchy with the help of C++ I think about:

Why there is no inheritance from the class objects? Abstract example (on abstract C++):

```<code>struct Foo { int v; Foo(int a) : v(a) {} };
struct Buz : public Foo(2) { ... }
</code>```

So, the Buz is inherited only from instance of Foo - Foo(2).

Can such idea be useful? Is there any possible implementations or related ideas?

答:
C++ has what you're describing, but the initialization is done as part of the constructor:</p>

```<code>struct Buz : public Foo {
  Buz() : Foo(2) { ... };
};
</code>```

Title: Inheritance from the objects themselves

Body:
C++ has what you're describing, but the initialization is done as part of the constructor:

struct Buz : public Foo {
  Buz() : Foo(2) { ... };
};


答:
This was 2 friends working on a project together. This is now 3 entities doing business together. So get to business. Your work may have been pro-bono, but there's money involved now.

Talk to your friend about what his intentions are for you, with respect to the future of the project, while he still has a majority say in the matter. He may have every good intention, and still forget to consider you while he's caught up in the excitement of making his business deal, between his company and his investor(s).

Title: Can I (reasonably) refuse to sign an NDA for pro bono work?

Body:
A friend of mine (let's call him Joe) is working on a promising project, and has asked me for help. As a matter of friendship I agreed (orally) not to discuss the details, but now he has a potential investor who wants me to sign a non-disclosure agreement (NDA). Since thus far all my work has been pro bono I told Joe I am not comfortable putting myself under documented legal obligation without some kind of compensation for the risk. (It needn't be strictly financial. I would accept a small ownership stake or possibly even just guaranteed credits in the code and documentation.)

Is my request reasonable, or am I just introducing unnecessary complexity?


答:
Is there any possible implementations or related ideas?

Many languages that use prototype inheritance do things like this.

The issue you run into is that from a logic point of view, the concept is only useful in very dynamic languages where 'inheritance' doesn't mean much and the syntax is shorthand for 'put all the fields from X into Y' or in pure languages without mutable variables. If the language allows mutability even if you inherit from Foo(2) that doesn't mean it won't be Foo(3) tomorrow or that two Foo(2) instances are even equivalent - which runs you into issues when you try to see if Buz inherits from Foo(2).

Title: Inheritance from the objects themselves

Body:
Making new inheritance hierarchy with the help of C++ I think about:

Why there is no inheritance from the class objects? Abstract example (on abstract C++):

```<code>struct Foo { int v; Foo(int a) : v(a) {} };
struct Buz : public Foo(2) { ... }
</code>```

So, the Buz is inherited only from instance of Foo - Foo(2).

Can such idea be useful? Is there any possible implementations or related ideas?


问:
Interaction of a GUI-based App and Windows Service
I am working on personal project that will be designed to help manage my media library, specifically recordings created by Windows Media Center.

So I am going to have the following parts to this application:

A Windows Service that monitors the recording folder.  Once a new recording is completed that meets specific criteria, it will call several 3rd party CLI Applications to remove the commercials and re-encode the video into a more hard-drive friendly format.

A controller GUI to be able to modify settings of the service, specifically add new shows to watch for, and to modify parameters for the CLI Applications

A standalone (GUI-based) desktop application that can perform many of the same functions as the windows service, expect manually on specific files instead of automatically based on specific criteria.

(It should be mentioned that I have limited experience with an application of this complexity, and I have absolutely zero experience with Windows Services)

Since the 1st and 3rd bullet share similar functionality, my design plan is to pull the common functionality into a separate library shared by both parts of the application, but these 2 components do not need to interact otherwise.

The 2nd and 3rd bullets seem to share some common functionality, both will have a GUI, both will have to help define similar parameters (one to send to the service and the other to send directly to the CLI applications), so I can see some advantage to combining them into the same application.

On the other hand, the standalone application (bullet #3) really does not need to interact with the service at all, except for possibly sharing a few common default parameters that can easily be put into an XML in a common location, so it seems to make more sense to just keep everything separate.

The controller GUI (2nd bullet) is where I am stuck at the moment.

Do I just roll this functionality (allow for user interaction with the service to update settings and criteria) into the standalone application?  Or would it be a better design decision to keep them separate?  Specifically, I'm worried about adding the complexity of communicating with the Windows Service to the standalone application when it doesn't need it.

Is WCF the right approach to allow the controller GUI to interact with the Windows Service?  Or is there a better alternative?  At the moment, I don't envision a need for a significant amount of interaction, maybe just adding a new task once in a while and occasionally tweaking a parameter, but when something is changed, I do expect the windows service to immediately use the new settings.

答:
The term used for interaction between programs on the same machine is "inter-process communication" - this should help you search for options.  This answer suggests WCF is your best option (it will allow you to use named pipes for data transport, which is more efficient for your needs than HTTP).

Whether to split up your GUI apps is a matter of preference - it's all about usability - especially since you're the primary (only?) user.  Weigh the benefits of each.  For example:

Separate: Easier to get to exactly what you want to do (think about your use cases and how often each will be used). Simpler UIs - no clutter from controls unrelated to your current usage.

Together: One app to deploy. One app to find and launch. No accidentally opening the wrong one.

Shared code or GUI elements shouldn't be a consideration - they can be shared through a DLL just as easily as if they were being used in the same project.

One alternative is to combine everything, including the service, into single GUI app, which minimizes to the notifications area and launches on Windows startup.  The "service" portion could run in a background thread, and you could have a context menu on the notification icon to open the settings dialog or to start a manual run.  This replaces the need for inter-process communication with inter-thread communication, which is simpler to get working.


问:
"static" as a semantic clue about statelessness?
I've recently undertaken a refactoring of a medium sized project in Java to go back and add unit tests. When I realized what a pain it was to mock singletons and statics, I finally "got" what I've been reading about them all this time. (I'm one of those people that needs to learn from experience. Oh well.)

So, now that I'm using Spring to create the objects and wire them around, I'm getting rid of static keywords left and right. (If I could potentially want to mock it, it's not really static in the same sense that Math.abs() is, right?) The thing is, I had gotten into the habit of using static to denote that a method didn't rely on any object state. For example:

```<code>//Before
import com.thirdparty.ThirdPartyLibrary.Thingy;
public class ThirdPartyLibraryWrapper {
    public static Thingy newThingy(InputType input) {
         new Thingy.Builder().withInput(input).alwaysFrobnicate().build();
    }
}

//called as...
ThirdPartyLibraryWrapper.newThingy(input);
</code>```

```<code>//After
public class ThirdPartyFactory {
    public Thingy newThingy(InputType input) {
         new Thingy.Builder().withInput(input).alwaysFrobnicate().build();
    }
}

//called as...
thirdPartyFactoryInstance.newThingy(input);
</code>```

So, here's where it gets touchy-feely. I liked the old way because the capital letter told me that, just like Math.sin(x), ThirdPartyLibraryWrapper.newThingy(x) did the same thing the same way every time. There's no object state to change how the object does what I'm asking it to do. Here are some possible answers I'm considering.

Nobody else feels this way so there's something wrong with me. Maybe I just haven't really internalized the OO way of doing things! Maybe I'm writing in Java but thinking in FORTRAN or somesuch. (Which would be impressive since I've never written FORTRAN.)

Maybe I'm using staticness as a sort of proxy for immutability for
the purposes of reasoning about code. That being said, what clues
should I have in my code for someone coming along to maintain it to know what's stateful and what's not?

Perhaps this should just come for free if I choose good object metaphors? e.g. thingyWrapper doesn't sound like it has state indepdent of the wrapped Thingy which may itself be mutable. Similarly, a thingyFactory sounds like it should be immutable but could have different strategies that are chosen among at creation.

答:
That being said, what clues should I have in my code for someone coming along to maintain it to know what's stateful and what's not?

You can make them static. FxCop over in the C# world will push you to make things static that do no reference member variables. This is the correct thing to do (usually).

When I realized what a pain it was to mock singletons and statics, I finally "got" what I've been reading about them all this time.

Moving all of them to instances is perhaps not the right approach. Instead, decouple the dependencies on static methods from the classes that use them. You can test the static methods in isolation, and then replace the dependency in the consumers when they need to be tested.


问:
What is the difference between a Program Manager and a Project Manager?
Is a Program Manager a person who manages mutiple projects (under a single program) which are in turn managed by Project Managers?

Or is a Program Manager a person as defined by Joel Spolsky here.

NOTE: I am not referring to this.

答:
I suppose the answer hinges on what the terms "Program" and "Project" mean.

According to Project Management Institute (PMI), The Standard for Program Management, 2nd Ed., "A Program is a group of related projects managed in a coordinated way to obtain benefits and control NOT available from managing them individually. Programs may include elements of related work outside of the scope of the discreet projects in the program... Some projects within a program can deliver useful incremental benefits to the organization before the program itself has completed."


答:
In my opinion what you are saying - all static functions to be nullipotent - is a good OO way of writing code in most cases but I do not believe that when you look at a static function you should automatically assume that it does not have side effects. The situation may be more complex; take for example the function Class.forName(String) which appears to be stateless but it actually loads a class into the memory and eventually instantiates static fields/run static initializer; this is an example of idempotent function (eventual calls after the first one make no difference) but it is not a pure function (it cannot be said that it does not have side-effects). This is also a good choice, but there might be cases in which three distinct calls to the same function yield three different results; for example if you call Thread.currentThread() in a multi-threaded application there is no guarantee you will receive the same thread every time.

That being said, what clues should I have in my code for someone
  coming along to maintain it to know what's stateful and what's not?

A proper solution is to document (Javadoc for example); also, from the name of the function and from what it does sometimes it can be inferred that the static function is a pure function. For example there is no reason for someone to believe that Assert.assertTrue(boolean) from JUnit would change some state somewhere. On the other hand when a function like System.clearProperty(String) is called, it is pretty obvious that there will be side-effects.

Title: "static" as a semantic clue about statelessness?

Body:
I've recently undertaken a refactoring of a medium sized project in Java to go back and add unit tests. When I realized what a pain it was to mock singletons and statics, I finally "got" what I've been reading about them all this time. (I'm one of those people that needs to learn from experience. Oh well.)

So, now that I'm using Spring to create the objects and wire them around, I'm getting rid of static keywords left and right. (If I could potentially want to mock it, it's not really static in the same sense that Math.abs() is, right?) The thing is, I had gotten into the habit of using static to denote that a method didn't rely on any object state. For example:

```<code>//Before
import com.thirdparty.ThirdPartyLibrary.Thingy;
public class ThirdPartyLibraryWrapper {
    public static Thingy newThingy(InputType input) {
         new Thingy.Builder().withInput(input).alwaysFrobnicate().build();
    }
}

//called as...
ThirdPartyLibraryWrapper.newThingy(input);
</code>```

```<code>//After
public class ThirdPartyFactory {
    public Thingy newThingy(InputType input) {
         new Thingy.Builder().withInput(input).alwaysFrobnicate().build();
    }
}

//called as...
thirdPartyFactoryInstance.newThingy(input);
</code>```

So, here's where it gets touchy-feely. I liked the old way because the capital letter told me that, just like Math.sin(x), ThirdPartyLibraryWrapper.newThingy(x) did the same thing the same way every time. There's no object state to change how the object does what I'm asking it to do. Here are some possible answers I'm considering.

Nobody else feels this way so there's something wrong with me. Maybe I just haven't really internalized the OO way of doing things! Maybe I'm writing in Java but thinking in FORTRAN or somesuch. (Which would be impressive since I've never written FORTRAN.)

Maybe I'm using staticness as a sort of proxy for immutability for
the purposes of reasoning about code. That being said, what clues
should I have in my code for someone coming along to maintain it to know what's stateful and what's not?

Perhaps this should just come for free if I choose good object metaphors? e.g. thingyWrapper doesn't sound like it has state indepdent of the wrapped Thingy which may itself be mutable. Similarly, a thingyFactory sounds like it should be immutable but could have different strategies that are chosen among at creation.


答:
I liked the old way because the capital letter told me that, just like
  Math.sin(x), ThirdPartyLibraryWrapper.newThingy(x) did the same thing
  the same way every time. There's no object state to change how the
  object does what I'm asking it to do.

That is the right way to do it, yes.  That said, static confers no guarantees of immutability or state persistence.  That you use it as a suggestion for such guarantees does make sense, but it is by no means assured.

Consider the following:

```<code>public static class Logger
{
    public static int LogLevel { get; set; }

    public static void Log(string message, int logLevel)
    {
        if (logLevel >= LogLevel)
        {
            // logs the message, but only if it is important enough.
        }
    }
}
</code>```

This class not only holds state, but the behavior of the Logger.Log() method changes when that state is changed.  It's a perfectly legitimate exercise of a static class pattern, but it has none of the semantic guarantees that you are suggesting.

Body:
I liked the old way because the capital letter told me that, just like
  Math.sin(x), ThirdPartyLibraryWrapper.newThingy(x) did the same thing
  the same way every time. There's no object state to change how the
  object does what I'm asking it to do.

That is the right way to do it, yes.  That said, static confers no guarantees of immutability or state persistence.  That you use it as a suggestion for such guarantees does make sense, but it is by no means assured.

Consider the following:

public static class Logger
{
    public static int LogLevel { get; set; }

    public static void Log(string message, int logLevel)
    {
        if (logLevel >= LogLevel)
        {
            // logs the message, but only if it is important enough.
        }
    }
}

This class not only holds state, but the behavior of the Logger.Log() method changes when that state is changed.  It's a perfectly legitimate exercise of a static class pattern, but it has none of the semantic guarantees that you are suggesting.


问:
How many bits' address is required for a computer with n bytes of memory?
How many bits of address is required (for the program counter for example) in a byte-addressed computer with 512 Mbyte RAM?

What does the formula look like?

How is this connected with the fact that 32 bits can address no more than 4 GB RAM?

答:
Existing answers have explained that the formula for addressing ram is 2^BITS = Addressable ram, but have not explained why.

Consider a system with 2 bits.  It can address 4 bytes of ram as follows:

Byte 0: 00

Byte 1: 01

Byte 2: 10

Byte 3: 11

For each additional bit, we can address twice as much memory.  E.g., add a 0 bit to each for bytes 0-3, then add a 1 bit for bytes 4-7.  We address byte X by using a bit arrangement corresponding to X in binary.


问:
Browser support for internal corporate tools
We are on the verge of a conversion.  For years, our company supported only IE for its internal (intranet) home-built tools.

Since a few of our users are still on XP, which means IE only goes up to 8... a heavily JS / jQuery site wont even load!

We have been in the process of converting to use Chrome instead, to make use of its javascript performance.

But, it has now been suggested that we support all common browsers... internally for these tools.  Which means more development time to scale-back some of these new applications, more time to test in all browsers, and we are already under staffed.

Are there any good informational sites/posts out there, that already make this argument?

答:
My company is currently going through a similar process, redeveloping old web-based software that was built for xp/ie set ups and moving staff onto Chrome. Fortunately we have quite a small team so moving everyone to Chrome and limiting support was doable, but when we were considering the other option it was helpful to keep this little gem in mind:

http://dowebsitesneedtolookexactlythesameineverybrowser.com

Quaint as it is the message is sound; as long as everyone is able to do everything that's needed you don't necessarily need to try and please everyone with one end-product. Consider focusing on progressive enhancement, maybe building something basic that does everything it needs to in IE but use heavier JavaScript in better browsers to enhance the interfaces, take advantage of AJAX etc.

Manage peoples expectations from the outset and you may even get people choosing to move from IE once they see the better experience they could have in another browser!


问:
Why do operating systems do low level stuff in C and C++? Why not just C++?
On the Wikipedia page for Windows, it states the Windows is written in Assembly for the bootloader and task switcher, and C and C++ for kernel routines.

IIRC, you can call C++ functions from an extern "C"'d block. I can get using C for the kernel functions so pure C apps can use them (like printf and such), but if they can just be wrapped in an extern "C " block, then why code in C?

答:
As most people have pointed out, reasons are by far historical, but there is something else no one is mentioning and I believe it is the reason people still write C code for low-level.

C is a small language in the sense that the spec is (relatively) short. C++ is huge and that's an understatement. This may not matter that much to the programmer (although I think it does), but it is extremely important if you want to do formal verification. Furthermore there are established tools for C code analysis, that could help prevent bugs, etc.

And this is very important in embedded software, where the cost of a bug that is deployed is extremely high, relative to the rest of the industry (compare Web, where you can apply a patch immediately to all users). Not to mention mission-critical software and medical stuff.

There have been attempts to displace C from its dominant place in low-level programming with languages that are even better at this, like BitC, but they haven't been successful so far.


问:
Is it appropriate for a class to only be a collection of information with no logic?
Say I have a class Person that has instance variables age, weight, and height, and another class Fruit that has instance variables sugarContent and texture. The Person class has no methods save setters and getters, while the Fruit class has both setters and getters and logic methods like calculateSweetness. Is the Fruit class the type of class that is better practice than the Person class. What I mean by this is that the Person class seems like it doesn't have much purpose; it exists solely to organize data, while the Fruit class organizes data and actually contains methods for logic.

答:
It sounds like what you are talking about is a POD (plain old data).  Different languages can represent these in different ways - it could be a class with public members for instance, or a struct with only public members in C++.

Organising data is a perfectly valid reason for a class to exist - it can often make code cleaner and easier to read.  std::pair in C++'s STL is a good example of a structure that exists solely to organise data - simply a struct that holds two values of any type named first and second.  Probably one the most useful classes in the entire STL (in my opinion anyways :) )


问:
Setting up ASP.NET structure for code
I've always coded in C# MVC3 when developing web applications. But now i wanted to learn a bit more about developing web sites with just ASP.NET.

But now i'm wondering what a good setup for my code would be. For me, an MVC like pattern seems to be a good way to go. But obviously ASP.NET doesn't have any router and controller classes. So i guess people have a different way of setting up their code when they do ASP.NET.

So i'm looking for more information on how to get started with this. So not really the basics of ASP.NET, but something that focuses on a good code setup.

Any good tutorials/information about this/?

答:
You can get very MVC-like in current versions of webforms; features such as routing and model binding have found ways into that part of the framework.

In general, the right way to do .NET apps on any platform is to build a core library that is UI agnostic and tie the UI layer in. If you do it right you can deal with anything -- be it WebForms, MVC, WPF or a console app -- without significant pain.

Title: Setting up ASP.NET structure for code


问:
Am I missing a pattern?
I have a class that is a singleton and off of the singleton are properties that hold the instances of all the performance counters in my application.

```<code>public interface IPerformanceCounters
    {
        IPerformanceCounter AccountServiceCallRate { get; }
        IPerformanceCounter AccountServiceCallDuration { get; }
</code>```

Above is an incomplete snippet of the interface for the class "PerformanceCounters" that is the singleton.

I really don't like the plural part of the name and thought about changing it to "PerformanceCounterCollection" but stopped because it really isn't a collection. I also thought about "PerformanceCounterFactory" but it is really a factory either. After failing with these two names and a couple more that aren't worth mentioning I thought that I might be missing a pattern.

Is there a name that make sense or a change that I could make towards a standardized pattern that would help me put some polish on this object and get rid of the plural name?

I understand that I might be splitting hairs here but that is why I thought that the "Programmers" exchange was the place for this kind of thing. If it is not... I am sorry and I will not make that mistake again.

Thanks!

答:
The term IPerformanceCounterSource could work, referring to a class that is a source of performance counters.

So long as the term is clear, you shouldn't have an issue.  While ~Collection or ~Set is gramatically correct, they could be confused for classes that take the form of ICollection.

Title: Am I missing a pattern?


问:
Scrum got specific ways for testing software?
When reading Scrum Guide, as the official text for scrum, I find out there is no specific solution to provide software testing in scrum. (the only hint is on page15)

I'm a little vague on whether scrum is considered a software development methodology or not?
If it is not, then how come some of its practices opposes Extreme Programming?
(I know that in scrum guide, the author notes that scrum is a framework not a methodology, but still I'm not pretty clear on that)

答:
Scrum is designed to help manage change in the project life cycle so that the customer can get what they need while allowing the team to develop the product effectively.

It leaves the actual implementation for how to go about achieving those goals open to the team, which is where methodologies like XP come into play.

It's better to look at Scrum as a software development management philosophy than as a software development methodology.  The last paragraph on page 15 brings this forward, emphasizing that Scrum works well as a container for other techniques, methodologies, and practices.


问:
Is there a good design pattern for this messaging class?
Is there a good design pattern for this?

I want to create a messaging class.

The class will be passed:

the type of message (eg. signup, signup confirmation, password reminder etc)
the client's id
The class needs to then look up the client's messaging preferences in the db (whether they want communication by email, sms or both)

Then depending on the client's preference it will format the message for the medium (short version for sms, long form for email) and send it through our mail or sms provider's API.

Because the fact that we want to be able to change out email and sms providers if need be I wondered if the Command Pattern would be a good choice.

答:
I would create an interface with the ability to return a short or long message. Then instantiate a class matching the type of message (signup) and send it to the correct transmission class (SMS), allowing the transmission class to interrogate the message for whatever information it needs (the short version of the message).

I am not sure off hand what design pattern that would be, but it keeps the implementation details as close as possible to their responsible parties I believe.


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
Someone much wiser than I once said:

The nun Wu Jincang asked the Sixth
  Patriach Huineng, "I have studied the
  Mahaparinirvana sutra for many years,
  yet there are many areas i do not
  quite understand. Please enlighten
  me."

The patriach responded, "I am
  illiterate. Please read out the
  characters to me and perhaps I will be
  able to explain the meaning."

Said the nun, "You cannot even
  recognize the characters. How are you
  able then to understand the meaning?"

"Truth has nothing to do with words.
  Truth can be likened to the bright
  moon in the sky. Words, in this case,
  can be likened to a finger. The finger
  can point to the moon’s location.
  However, the finger is not the moon.
  To look at the moon, it is necessary
  to gaze beyond the finger, right?"

Title: What's a nice explanation for pointers?


问:
How can I explain the usefulness of Inheritance?
When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

答:
Chemistry Elements Example

This is another example popped out of my brain:

```
class Element_
{
    double atomicWeight; //Atomic weight of element
    double atomicNumber; // Atomic number of element
    String Properties;  // Properties of element
    //Others, if any
}

class Isotope extends Element_  // There can exist Isotopes of element
{
    double halflife;
   //Others if any

}
```

Body:
Chemistry Elements Example

This is another example popped out of my brain:

class Element_
{
    double atomicWeight; //Atomic weight of element
    double atomicNumber; // Atomic number of element
    String Properties;  // Properties of element
    //Others, if any
}

class Isotope extends Element_  // There can exist Isotopes of element
{
    double halflife;
   //Others if any

}


答:
Bjarne Stroustrup, in an interview in July 1999:

None of these languages was radically different or dramatically
  better than other contemporary languages. They were, however, good
  enough and the beneficiaries of luck and social factors

Title: Why do operating systems do low level stuff in C and C++? Why not just C++?

Body:
On the Wikipedia page for Windows, it states the Windows is written in Assembly for the bootloader and task switcher, and C and C++ for kernel routines.

IIRC, you can call C++ functions from an extern "C"'d block. I can get using C for the kernel functions so pure C apps can use them (like printf and such), but if they can just be wrapped in an extern "C " block, then why code in C?


答:
Good example is the compare function in sorting:

```<code>template<class T>
class CompareInterface {
public:
   virtual bool Compare(T t1, T t2) const=0;
};
class FloatCompare : public CompareInterface<float> { };
class CompareImplementation : public FloatCompare {
public:
   bool Compare(float t1, float t2) const { return t1<t2; }
};
template<class T>
void Sort(T*array, int size, CompareInterface<T> &compare);
</code>```

The only problem is the newbies too often think performance is more important than good code...

Title: How can I explain the usefulness of Inheritance?

Body:
When trying to explain the concept of Inheritance in OOP, the common example is often the mammals example. IMHO, this is really a bad example, because it will lead the newbies to use this concept the wrong way. And moreover, it is not a common design that they will face in their day-to-day design job.

So, what will be a nice, simple and concrete problem that is solved using Inheritance ?

Body:
Good example is the compare function in sorting:

template<class T>
class CompareInterface {
public:
   virtual bool Compare(T t1, T t2) const=0;
};
class FloatCompare : public CompareInterface<float> { };
class CompareImplementation : public FloatCompare {
public:
   bool Compare(float t1, float t2) const { return t1<t2; }
};
template<class T>
void Sort(T*array, int size, CompareInterface<T> &compare);

The only problem is the newbies too often think performance is more important than good code...


答:
It's possible that the C parts are not nicely portable to the C++ compiler that is used for the C++ parts. Maybe the C code is chummy with the C compiler in ways that break with the C++ compiler.

If you have a quality C++ compiler, there is almost no reason to mix C and C++ in a project. Almost.

The one reason would be that your project shares C code with other projects, the code does not compile as C++, and you don't want to maintain a C++ fork of that that code.


问:
What patterns book for iOS development contains this specific information?
I've read several books on iOS development and Objective-C, however what a lot of them teach is how to work with interfaces and all contain the model inside the view controller, i.e. a UITableViewController based view will simply have an NSArray as it's model. I'm interested in what the best practices are for designing the structure of an application.

Specifically I'm interested in best practices for the following:

How to separate a model from the view controller. I think I know how to do this by simply replacing the NSArray style example with a specific model object, however what I do not know how to do is alert the view when the model changes. For example in .NET I would solve this by conforming to INotifyPropertyChanged and databinding, and similarly with Java I would use PropertyChangeListener.

How to create a service model for my domain objects. For example I want to learn the best way to create a service for a hypothetical Widget object to manage an internal DB and also services for communicating with remote endpoints. I need to learn the best ways to do this in a way that interface components can subscribe to events such as widgetUpdated. These services should be singleton classes and some how dependency injected into model/controller objects.

Books I've read so far are:

Programming in Objective-C (4th Edition)

Beginning iOS 5 Development: Exploring the iOS SDK

The iOS 5 Developer's Cookbook: Expanded Electronic Edition: Essentials and Advanced Recipes for iOS Programmers

Learn Objective-C on the Mac: For OS X and iOS

I've also purchased the following updated books but not yet read them.

The Core iOS 6 Developer's Cookbook (4th edition

Programming in Objective-C (5th Edition)

I come from a Java and C# background with 15 years experience, I understand that many of the ways I would do things in these languages may not fit to the ObjC way of developing applications.

Would someone be able to provide me with the book on this topic containing this specific subject matter?

答:
Cocoa Design Patterns by Erik Buck and Donald Yacktman is a good resource for understanding how various design patterns are used in Cocoa. Although the book is a couple years old and written for Cocoa rather than Cocoa Touch, the two frameworks are conceptually very similar, and the additions in iOS 5 and 6 do little to change the underlying ideas, especially the ones you're asking about.

How to separate a model from the view controller. I think I know how
  to do this by simply replacing the NSArray style example with a
  specific model object, however what I do not know how to do is alert
  the view when the model changes.

The model generally won't talk to the view directly -- it should go through the controller. You have a number of options in this respect, including but not limited to:

Have the view controller observe relevant parts of the model using Key Value Observing.

Use notifications.

If the model is changing due to user input, the view controller may know to expect some aspects of the model to change.

Use delegation. Define a delegate protocol for your model and adopt it in your view controller. Set the view controller as the model's delegate.

How to create a service model for my domain objects...

From your comment I see that you're looking for a way to manage your graph of model objects. The Core Data framework provides object graph management and persistence -- it makes it easy to work with your data as objects without having to worry about how to store it all in database tables. It's fast and performs well even with relatively large amounts of data.


答:
The C runtime is much smaller.

The translation of C++ into lower-level constructs is less transparent than in C.  (See references and vtables, for two quick examples)

C usually has a stable ABI.  C++ usually does not.  This means that at the bare minimum, the system call interface should be C style.  In addition, if you want any sort of dynamic modules, having a consistent ABI helps greatly.


问:
GMail API for a small app (Rails? Javascript? PHP?)
I want to create an app that accesses the GMail API, but I'm finding that it isn't as simple as I thought it might be.

I'm hoping somebody in the community here might have some experience working with one of these API's and could not only recommend the right solution, but also show me to some tutorials or examples that could help me get up and running.

Here are some of the requirements of this app:

Preferably in Rails or Javascript or even PHP. I am open to other technologies as well, but hope they'd be easy to implement.

Connects to gmail via Oauth

Can read who emails have been sent to and received from. Basically would like to perform some analytics on who emails are sent to, when and how frequently.

I've read that one reason why this isn't easy, and why there isn't an official javascript API provided by gmail, is that google is concerned it's going to make their service less performant for their users.

答:
This will help . You will just get the concepts regarding web services . IMAP , SMTP but not for specific language .

https://developers.google.com/google-apps/gmail/


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

答: Critical and logical thinking. you can't do anything good without it.</p>


答: The trick is to explain that the location of a thing and the thing itself are not the same, just like a picture of a pipe is not a pipe. When you move a thing, its location changes. The location remains and some other thing can be put there.</p>

Title: What's a nice explanation for pointers?

Body:
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.


问:
Is Extreme Programming (XP) the best way of learning from experts?
I have been involved in many development models, and have found XP to be the best for a new programmer from the aspect of learning, as the collaboration between the team members is very high and the opportunities to share knowledge are great.

What are the expert opinions on this?

答:
While I'm not an expert, there are different ways that people learn things which should be acknowledged.  Some people can handle being given all the abstract details and then go and implement it with little difficulty while others would struggle to get through the first example.  If the expert goes too fast, bullies the other developer, or uses language that the other developer doesn't understand this can cause problems for the non-expert and thus not be the best way to learn.

I have seen coding camp examples done where I learned a lot though this is from watching and absorbing what is being shown.  While having a consultant can be useful, it can also be overwhelming in some cases to try to absorb so much if they are only there for a short time.  Some of what was shown is still with me, but other parts are long gone.


答:
Great question. I've struggled with finding the best way to build objective-c apps which adhering to MVC and I find that the using delegates is often the cleanest approach to synchronize views with models.

So, if your model is loading something over the network, the delegate might look like this:

```<code>@protocol XXItemLoadDelegate <NSObject>
- (void) willLoadItemWithIdentifier:(NSString*)identifier;
- (void) didLoadItem:(XXItem*)item;
- (void) didFailToLoadWithError:(NSError*)error;
@end
</code>```

And I think it's clear how a view might show/hide a busy indicator and then update once the item loaded.

The main disadvantages to the delegate pattern are:

forgetting to set the delegate

forgetting to call the delegate events in the model

overwriting the delegate (when multiple views want to be notified)

reseting the delegate (e.g. if a view is reused, the delegate should be nil first)

painful to refactor if you decide you need multiple observers

giving the the protocol and delegate methods consistent names

Despite all these drawbacks, I prefer the explicitness of delegates to other approaches.

NSNotifications are great for keeping completely unrelated pieces of code synchronized. But I've found they should be used sparingly, as it makes code incredibly hard to trace and debug.

KVO is also an option for syncing views to models, but I don't have much experience with using it in larger projects.

I didn't much care for the Cocoa Design Patterns book. It seemed out-of-date, and didn't have as much practical information as I would have hoped.

Instead of books, I'd also recommend reading through larger iOS projects on github. You can always see some design patters in action - and learn a few good tricks. For example:

App Sales Mobile

Title: What patterns book for iOS development contains this specific information?

Body:
I've read several books on iOS development and Objective-C, however what a lot of them teach is how to work with interfaces and all contain the model inside the view controller, i.e. a UITableViewController based view will simply have an NSArray as it's model. I'm interested in what the best practices are for designing the structure of an application.

Specifically I'm interested in best practices for the following:

How to separate a model from the view controller. I think I know how to do this by simply replacing the NSArray style example with a specific model object, however what I do not know how to do is alert the view when the model changes. For example in .NET I would solve this by conforming to INotifyPropertyChanged and databinding, and similarly with Java I would use PropertyChangeListener.

How to create a service model for my domain objects. For example I want to learn the best way to create a service for a hypothetical Widget object to manage an internal DB and also services for communicating with remote endpoints. I need to learn the best ways to do this in a way that interface components can subscribe to events such as widgetUpdated. These services should be singleton classes and some how dependency injected into model/controller objects.

Books I've read so far are:

Programming in Objective-C (4th Edition)

Beginning iOS 5 Development: Exploring the iOS SDK

The iOS 5 Developer's Cookbook: Expanded Electronic Edition: Essentials and Advanced Recipes for iOS Programmers

Learn Objective-C on the Mac: For OS X and iOS

I've also purchased the following updated books but not yet read them.

The Core iOS 6 Developer's Cookbook (4th edition

Programming in Objective-C (5th Edition)

I come from a Java and C# background with 15 years experience, I understand that many of the ways I would do things in these languages may not fit to the ObjC way of developing applications.

Would someone be able to provide me with the book on this topic containing this specific subject matter?

Body:
Great question. I've struggled with finding the best way to build objective-c apps which adhering to MVC and I find that the using delegates is often the cleanest approach to synchronize views with models.

So, if your model is loading something over the network, the delegate might look like this:

@protocol XXItemLoadDelegate <NSObject>
- (void) willLoadItemWithIdentifier:(NSString*)identifier;
- (void) didLoadItem:(XXItem*)item;
- (void) didFailToLoadWithError:(NSError*)error;
@end

And I think it's clear how a view might show/hide a busy indicator and then update once the item loaded.

The main disadvantages to the delegate pattern are:

forgetting to set the delegate

forgetting to call the delegate events in the model

overwriting the delegate (when multiple views want to be notified)

reseting the delegate (e.g. if a view is reused, the delegate should be nil first)

painful to refactor if you decide you need multiple observers

giving the the protocol and delegate methods consistent names

Despite all these drawbacks, I prefer the explicitness of delegates to other approaches.

NSNotifications are great for keeping completely unrelated pieces of code synchronized. But I've found they should be used sparingly, as it makes code incredibly hard to trace and debug.

KVO is also an option for syncing views to models, but I don't have much experience with using it in larger projects.

I didn't much care for the Cocoa Design Patterns book. It seemed out-of-date, and didn't have as much practical information as I would have hoped.

Instead of books, I'd also recommend reading through larger iOS projects on github. You can always see some design patters in action - and learn a few good tricks. For example:

App Sales Mobile


问:
share code between check and process methods
My job is to refactor an old library for GIS vector data processing. The main class encapsulates a collection of building outlines, and offers different methods for checking data consistency. Those checking functions have an optional parameter that allows to perform some process. For instance:

```<code>std::vector<Point> checkIntersections(int process_mode = 0);
</code>```

This method tests if some building outlines are intersecting, and return the intersection points. But if you pass a non null argument, the method will modify the outlines to remove the intersection.

I think it's pretty bad (at call site, a reader not familiar with the code base will assume that a method called checkSomething only performs a check and doesn't modifiy data) and I want to change this.
I also want to avoid code duplication as check and process methods are mostly similar.

So I was thinking to something like this:

```<code>// a private worker
std::vector<Point> workerIntersections(int process_mode = 0)
{
    // it's the equivalent of the current checkIntersections, it may perform
    // a process depending on process_mode
}

// public interfaces for check and process
std::vector<Point> checkIntersections()  /* const */
{
    workerIntersections(0);
}

std::vector<Point> processIntersections(int process_mode /*I have different process modes*/)
{
    workerIntersections(process_mode);
}
</code>```

But that forces me to break const correctness as workerIntersections is a non-const method.

How can I separate check and process, avoiding code duplication and keeping const-correctness?

答:
Just change the name of checkIntersections to checkOrProcessIntersections.

On more serious note :-

You said this is an old library. So if you change the behaviour isn't the old customer will be affected? My advice will be to keep the checkIntersections. Add two more methods strictCheckIntesection or onlyCheckIntersection and processIntersections. And then from your checkIntersections call these two methods, depending on the input parameter.

Also didn't get your worry about the constness. If some function is changing the state, it is changing the state. It is not going to be const in any case.


问:
When do you use a struct instead of a class?
What are your rules of thumb for when to use structs vs. classes?  I'm thinking of the C# definition of those terms but if your language has similar concepts I'd like to hear your opinion as well.

I tend to use classes for almost everything, and use structs only when something is very simplistic and should be a value type, such as a PhoneNumber or something like that.  But this seems like a relatively minor use and I hope there are more interesting use cases.

答:
The answer: "Use a struct for pure data constructs, and a class for objects with operations" is definitely wrong IMO.  If a struct holds a large number of properties then a class is nearly always more appropriate.  Microsoft often says, from an efficiency point of view, if your type is larger than 16 bytes it should be a class.

https://stackoverflow.com/questions/1082311/why-should-a-net-struct-be-less-than-16-bytes

ContentLicense: CC BY-SA 4.0


问:
Is there any way to test how will the site perform under load
I have made an Asp.net MVC website and hosted it on a shared hosting provider. Since my website surrounds a very generic idea, it might have number of concurrent users sometime in future.

So, I was thinking of a way to test my website for on-load performance. Like how will the site perform when 100 or 1000 users are online at the same time and surfing the website. This will also make me understand whether my LINQ queries are well written or not.

答: I don't think load testing can be done manually as it will consume more time than expected and will be a tedious task. You can probably go for Load Runner which can go for many users.</p>


问:
Is there a manageable way of keeping track of loose code?
I program simple tasks everyday, but I have a hard time finding the scripts, and code snippets I write. Is there an manageable way to keep track of this sort of thing?</p>

答: Try bookmarking your code with reminder comments. That will help you a lot. Also there are a variety of great source control management systems available in the market. </p>


答:
8-10 years ago, I taught an intro "C" course at a community college. This was always a fun topic to explore. What seemed to work best, and this was after discussing w/ a co-worker a few times was to use a coffee cup and your hand.

I used the analogy of a coffee cup (or row of them for arrays) to as a variable (it can hold something). I then used my hand, which could also hold something or, by extending my index finger to "point to" a coffee cup.

A close hand was null, a finger pointing at my head (like a mock gun) was a dangling pointer.

Then with a few demonstrations and trips through the debugger, it clicked with most.

Title: What's a nice explanation for pointers?


问:
Representing complex object dependencies
I have several classes with a reasonably complex (but acyclic) dependency graph. All the dependencies are of the form: class X instance contains an attribute of class Y. All such attributes are set during initialization and never changed again.

Each class' constructor has just a couple parameters, and each object knows the proper parameters to pass to the constructors of the objects it contains. class Outer is at the top of the dependency hierarchy, i.e., no class depends on it.

Currently, the UI layer only creates an Outer instance; the parameters for Outer constructor are derived from the user input. Of course, Outer in the process of initialization, creates the objects it needs, which in turn create the objects they need, and so on.

The new development is that the a user who knows the dependency graph may want to reach deep into it, and set the values of some of the arguments passed to constructors of the inner classes (essentially overriding the values used currently). How should I change the design to support this?

I could keep the current approach where all the inner classes are created by the classes that need them. In this case, the information about "user overrides" would need to be passed to Outer class' constructor in some complex user_overrides structure. Perhaps user_overrides could be the full logical representation of the dependency graph, with the overrides attached to the appropriate edges. Outer class would pass user_overrides to every object it creates, and they would do the same. Each object, before initializing lower level objects, will find its location in that graph and check if the user requested an override to any of the constructor arguments.

Alternatively, I could rewrite all the objects' constructors to take as parameters the full objects they require. Thus, the creation of all the inner objects would be moved outside the whole hierarchy, into a new controller layer that lies between Outer and UI layer. The controller layer would essentially traverse the dependency graph from the bottom, creating all the objects as it goes. The controller layer would have to ask the higher-level objects for parameter values for the lower-level objects whenever the relevant parameter isn't provided by the user.

Neither approach looks terribly simple. Is there any other approach? Has this problem come up enough in the past to have a pattern that I can read about? I'm using Python, but I don't think it matters much at the design level.

答:
An approach using reflection might work well here.

So, assuming if it's ok to set up the graph in the default way, and then set values that you wish to override after (which requires mutability of your objects, obviously):

Have your object graph set up in the default way. Then use reflection to walk the object graph. For each object you find in the graph, check for any properties represented in your user_overrides helper structure for overriding. If you find a match, set the property to the new value (again, using reflection).

Depending on your exact scenario, you may just be able to match against class types in your user_overrides structure; alternatively, you might have to store keypaths, by which I mean something representing the route to a certain class in the object graph.

You may have to be careful about the order in which you override things in the object tree.

There's plenty of info out there about reflection.


问:
OO Design, how to model Tonal Harmony?
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.

答:
I think the best approach is to reproduce the real relationships between these entities.

For example, you could have:

a Note object, whose properties are

name (C, D, E, F, G, A, B)

accidental (natural, flat, sharp)

frequency or another unique pitch identifier

a Chord object, whose properties are

an array of Note objects

name

accidental

quality (major, minor, diminished, augmented, suspended)

additions (7, 7+, 6, 9, 9+, 4)

a Scale object, whose properties are

an array of Note objects

name

type (major, natural minor, melodic minor, harmonic minor)

mode (ionian, dorian, phrygian, lydian, mixolidian, aeolian, locrian)

Then, if your input is textual, you can create notes with a string including the note name, accidental and (if you need it) octave.

For example (pseudocode, I don't know C++):

```<code>note = new Note('F#2');
</code>```

Then, in the Note class you can parse the string and set the properties.

A Chord could be constructed by its notes:

```<code>chord = new Chord(['C2', 'E2', 'G2']);
</code>```

...or by a string including name, quality and additional notes:

```<code>chord = new Chord('Cmaj7');
</code>```

I don't know what your application will do exactly, so these are just ideas.

Good luck with your fascinating project!

Title: OO Design, how to model Tonal Harmony?

Body:
I think the best approach is to reproduce the real relationships between these entities.

For example, you could have:

a Note object, whose properties are

name (C, D, E, F, G, A, B)

accidental (natural, flat, sharp)

frequency or another unique pitch identifier

a Chord object, whose properties are

an array of Note objects

name

accidental

quality (major, minor, diminished, augmented, suspended)

additions (7, 7+, 6, 9, 9+, 4)

a Scale object, whose properties are

an array of Note objects

name

type (major, natural minor, melodic minor, harmonic minor)

mode (ionian, dorian, phrygian, lydian, mixolidian, aeolian, locrian)

Then, if your input is textual, you can create notes with a string including the note name, accidental and (if you need it) octave.

For example (pseudocode, I don't know C++):

note = new Note('F#2');

Then, in the Note class you can parse the string and set the properties.

A Chord could be constructed by its notes:

chord = new Chord(['C2', 'E2', 'G2']);

...or by a string including name, quality and additional notes:

chord = new Chord('Cmaj7');

I don't know what your application will do exactly, so these are just ideas.

Good luck with your fascinating project!


答:
I use Mercurial for this. My work is on both Linux and Windows, so I have such small code snippets for both the system. I have created a repository on windows, on which I save all this scripts and then the clone of this on linux. I keep both in sync.

Other than the use of DVCS, I also have a single csv text file which works as a key, value pair. The key is a small description of a program and value is it's location on the repository. Whatever I need I search in this file, and also keeps this file up-to-date. No need to tell that this file is also part of the repository.

Let me warn you that, It has taken lots of efforts and discipline to make a habit of keeping things clean and neat.

For Git lovers, I also love Git and also have repository in Github. It just that Mercurial is our official DVCS.

Title: Is there a manageable way of keeping track of loose code?

Body: I program simple tasks everyday, but I have a hard time finding the scripts, and code snippets I write. Is there an manageable way to keep track of this sort of thing?</p>


答:
Your description of user_overrides is beginning to sound a bit like the strategy pattern - where objects outside of the hierarchy pass a strategy (callback) for creating the dependency..

example in pseudocode

```<code>type OuterType
{
    private inner : InnerType

    // Existing behaviour - concrete Inner instantiation is hard coded
    OuterConstructor()
    {
        _inner = new Inner()
    }

    // Strategy pattern, instantiation strategy is passed from outside as
    // a callback function which returns an Inner instance
    OuterConstructor(func() innerBuilderCallback)
    {
        _inner = innerBuilderCallback()
    }
}
</code>```

What happens if Inner also has a dependency which you want to expose with an instantiation strategy? You don't have to pass both strategies to the Outer constructor, since that strategy will itself 'chain' the nested strategy

```<code>void Foo()
{
    func innerBuilderCallback = lambda: new Inner(lambda: new InnerDependency());

    var outer = new Outer(innerBuilderCallback);
}
</code>```

Depending on how deep your hierarchy goes, you might find that you end up with quite a few of these callback strategies which becomes a little difficult to manage. In that case, encapsulate the whole process in a Factory object.

Title: Representing complex object dependencies

Body:
I have several classes with a reasonably complex (but acyclic) dependency graph. All the dependencies are of the form: class X instance contains an attribute of class Y. All such attributes are set during initialization and never changed again.

Each class' constructor has just a couple parameters, and each object knows the proper parameters to pass to the constructors of the objects it contains. class Outer is at the top of the dependency hierarchy, i.e., no class depends on it.

Currently, the UI layer only creates an Outer instance; the parameters for Outer constructor are derived from the user input. Of course, Outer in the process of initialization, creates the objects it needs, which in turn create the objects they need, and so on.

The new development is that the a user who knows the dependency graph may want to reach deep into it, and set the values of some of the arguments passed to constructors of the inner classes (essentially overriding the values used currently). How should I change the design to support this?

I could keep the current approach where all the inner classes are created by the classes that need them. In this case, the information about "user overrides" would need to be passed to Outer class' constructor in some complex user_overrides structure. Perhaps user_overrides could be the full logical representation of the dependency graph, with the overrides attached to the appropriate edges. Outer class would pass user_overrides to every object it creates, and they would do the same. Each object, before initializing lower level objects, will find its location in that graph and check if the user requested an override to any of the constructor arguments.

Alternatively, I could rewrite all the objects' constructors to take as parameters the full objects they require. Thus, the creation of all the inner objects would be moved outside the whole hierarchy, into a new controller layer that lies between Outer and UI layer. The controller layer would essentially traverse the dependency graph from the bottom, creating all the objects as it goes. The controller layer would have to ask the higher-level objects for parameter values for the lower-level objects whenever the relevant parameter isn't provided by the user.

Neither approach looks terribly simple. Is there any other approach? Has this problem come up enough in the past to have a pattern that I can read about? I'm using Python, but I don't think it matters much at the design level.

Body:
Your description of user_overrides is beginning to sound a bit like the strategy pattern - where objects outside of the hierarchy pass a strategy (callback) for creating the dependency..

example in pseudocode

type OuterType
{
    private inner : InnerType

    // Existing behaviour - concrete Inner instantiation is hard coded
    OuterConstructor()
    {
        _inner = new Inner()
    }

    // Strategy pattern, instantiation strategy is passed from outside as
    // a callback function which returns an Inner instance
    OuterConstructor(func() innerBuilderCallback)
    {
        _inner = innerBuilderCallback()
    }
}

What happens if Inner also has a dependency which you want to expose with an instantiation strategy? You don't have to pass both strategies to the Outer constructor, since that strategy will itself 'chain' the nested strategy

void Foo()
{
    func innerBuilderCallback = lambda: new Inner(lambda: new InnerDependency());

    var outer = new Outer(innerBuilderCallback);
}

Depending on how deep your hierarchy goes, you might find that you end up with quite a few of these callback strategies which becomes a little difficult to manage. In that case, encapsulate the whole process in a Factory object.


问:
Mobile Compatibility: traditional website look vs native application ?
I have a question related to mobile compatible websites, I have seen two type of websites

One in which they adopt traditional website look and adjust website according to mobile screen, if they have lot of information which can not be adjust according to screen then they expand the height of page, so that user can scroll the page to see more information...

In the second approach they used native application look means use navigation-bar, tab-bar, tool-bar, scroll-view just like in native applications. Height and width of page adjust according to screen size, if they have more information then they use scroll-view etc...

My question is: which approach is better then other, in which approach you feel more comfortable to use website.

答:
If you are talking about mobile sites and mobile applications, then  here interesting research Mobile Sites vs. Apps: The Coming Strategy Shift. In short, Jakob Nielsen recommend to build Mobile application if you have a budget for it, but he predict, that in future mobile version of site will be more preferable solution.

Basanta Tandon in presentaion: Mobile Site vs. Apps – Comparison and Best Practices propose a little bit another view on this problem.
He propose to build native application in following cases:

2-10% of your visitors are coming via the mobile devices

There’s a need for built-in hardware features

Focused marketing in an App store

In my opinion, it's good to build mobile application for website. But It should be as an additional features, not just to provide another way to access website information. Mobile application can really different usability and application developers should use this to improve loyalty of audience.


答:
I would move all object construction logic out of Outer into a different class using the Factory_pattern.

The Constructors of domain-classes ´Outer´ and ´Inner´ get all required child parameters

```<code>public Outer(Inner inner)
{
    _inner = inner;
}
</code>```

and the factory create the items for you:

```<code>public class OuterFactory
{
    // Existing behaviour - concrete Inner instantiation is hard coded
    public virtual Outer createOuter(CreationParameters parameters)
    {
        Inner _inner = createInner(parameters);
        Outer outer = new Outer(inner);

        return outer;
    }

    public virtual Inner createInner(CreationParameters parameters)
    {
        Inner _inner = new Inner();
        return _inner;
    }
}
</code>```

If you need a different inner class you can easily create a new factory that derives from the base factory:

```<code>public class MySpecialOuterFactory : OuterFactory
{
    public overrrde Inner createInner(CreationParameters parameters)
    {
        Inner _inner = new SpecialInner();
        return _inner;
    }
}
</code>```

Body:
I would move all object construction logic out of Outer into a different class using the Factory_pattern.

The Constructors of domain-classes ´Outer´ and ´Inner´ get all required child parameters

public Outer(Inner inner)
{
    _inner = inner;
}

and the factory create the items for you:

public class OuterFactory
{
    // Existing behaviour - concrete Inner instantiation is hard coded
    public virtual Outer createOuter(CreationParameters parameters)
    {
        Inner _inner = createInner(parameters);
        Outer outer = new Outer(inner);

        return outer;
    }

    public virtual Inner createInner(CreationParameters parameters)
    {
        Inner _inner = new Inner();
        return _inner;
    }
}

If you need a different inner class you can easily create a new factory that derives from the base factory:

public class MySpecialOuterFactory : OuterFactory
{
    public overrrde Inner createInner(CreationParameters parameters)
    {
        Inner _inner = new SpecialInner();
        return _inner;
    }
}


问:
How does one read RFCs and similar documents?
RFC:

Request for Comments (RFC) is a memorandum published by the Internet
  Engineering Task Force (IETF) describing methods, behaviors, research,
  or innovations applicable to the working of the Internet and
  Internet-connected systems.

At the end of this Intro to REST video, RFC2616 and RFC3986 are mentioned as further reading. After watching the video, I googled those documents and, as the title suggests, I'm not sure how to use them. Do I read them in their entirety and make notes or do I use them more as a reference for when I don't understand something or have a problem?

答:
As you state in your question, the RFCs are either de facto standards for internet operations or they provide additional guidance for those operations.  Their appendix regarding RFCs does a better job at illuminating the various sources of RFCs and their overall meaning, including considerations of obsolescence.

Do I read them in their entirety and make notes or do I use them more as a reference for when I don't understand something or have a problem?

Treat them like you would treat any other standards reference.

Some folk like to read a reference all the way through; it gives them a very solid understanding of what's required.

Others will skim through a standard and refer back to it when they run into problems that the RFC should address.

Others still will never peruse the contents of an RFC.

In general, I think they are much more useful as a reference than as explanatory text.  But I fall into the second category of people that I described.  On the other hand, if you're really wanting to understand the nuts and bolts of a particular technology then you may want to dive deeply into the standard.  As with so many things, it depends upon what your aims are.

For what you're doing with the REST tutorial, option #2 is probably your best bet.  Skim, glean something new, refer back as necessary.


答:
Sounds like a case for templates. You seem to have a template <?> class Major : public Chord; so Major<C> is-a Chord, as is Major. Similarly, you also have a Note<?> template with instances Note<C> and Note<D>.

The only thing I've left out is the ? part. It seems you have an enum {A,B,C,D,E,F,G} but I don't know how you'd name that enum.

Title: OO Design, how to model Tonal Harmony?

Body:
I have started to write a program in C++ 11 that would analyse chords, scales, and harmony.
The biggest problem I am having in my design phase, is that the note 'C' is a note, a type of chord (Cmaj, Cmin, C7, etc), and a type of key (the key of Cmajor, Cminor). The same issue arises with intervals (minor 3rd, major 3rd).

I am using a base class, Token, that is the base class for all 'symbols' in the program. so for example:

```<code>class Token {
public:
    typedef shared_ptr<Token> pointer_type;
    Token() {}
    virtual ~Token() {}
};

class Command : public Token {
public:
    Command() {}
    pointer_type execute();
}

class Note : public Token;

class Triad : public Token; class MajorTriad : public Triad; // CMajorTriad, etc

class Key : public Token; class MinorKey : public Key; // Natural Minor, Harmonic minor,etc

class Scale : public Token;
</code>```

As you can see, to create all the derived classes (CMajorTriad, C, CMajorScale, CMajorKey, etc) would quickly become ridiculously complex including all the other notes, as well as enharmonics. multiple inheritance would not work, ie:

```<code>class C : public Note, Triad, Key, Scale
</code>```

class C, cannot be all of these things at the same time. It is contextual, also polymorphing with this will not work (how to determine which super methods to perform? calling every super class constructors should not happen here)

Are there any design ideas or suggestions that people have to offer? I have not been able to find anything on google in regards to modelling tonal harmony from an OO perspective. There are just far too many relationships between all the concepts here.

Body:
Sounds like a case for templates. You seem to have a template <?> class Major : public Chord; so Major<C> is-a Chord, as is Major<B>. Similarly, you also have a Note<?> template with instances Note<C> and Note<D>.

The only thing I've left out is the ? part. It seems you have an enum {A,B,C,D,E,F,G} but I don't know how you'd name that enum.


问:
Should I use a parser generator or should I roll my own custom lexer and parser code?
What specific advantages and disadvantages of each way to working on a programming language grammar?

Why/When should I roll my own? Why/When should I use a generator?

答:
The advantage of writing your own recursive descent parser is that you can generate high-quality error messages on syntax errors. Using parser generators, you can make error productions and add custom error messages at certain points, but parser generators just don't match the power of having complete control over the parsing.

Another advantage of writing your own is that it is easier to parse to a simpler representation that doesn't have a one to one correspondence to your grammar.

If your grammar is fixed, and error messages are important, consider rolling your own, or at least using a parser generator that gives you the error messages you need. If your grammar is constantly changing, you should consider using parser generators instead.

Bjarne Stroustrup talks about how he used YACC for the first implementation of C++ (see The Design and Evolution of C++). In that first case, he wished he wrote his own recursive descent parser instead!


答:
It may depend on why and for what you read it. Actually you will find, that many programmers never ever read such documents at all. So lets handle the exception:

You are very curious and want to know everything about a certain technology. Then you simply read them and take notes as you want or find necessary. Or just read through them so you have a good idea what to find there (plus: can give really smart answers on StackOverflow and get lots of reputation)

You need to prepare for a test about it. (Handle as test preparation for everything else, take a lot of notes)

You need to implement a piece of software that depends on rigorous correct implementation of something (a web browser the URI handling, any compiler or interpreter for a given language). In this case you read very careful, take lots of notes and at the same time develop various test cases against which to run your program.

Title: How does one read RFCs and similar documents?

Body:
RFC:

Request for Comments (RFC) is a memorandum published by the Internet
  Engineering Task Force (IETF) describing methods, behaviors, research,
  or innovations applicable to the working of the Internet and
  Internet-connected systems.

At the end of this Intro to REST video, RFC2616 and RFC3986 are mentioned as further reading. After watching the video, I googled those documents and, as the title suggests, I'm not sure how to use them. Do I read them in their entirety and make notes or do I use them more as a reference for when I don't understand something or have a problem?


答:
As others have already said, a VCS alone is not enough for this. What your really need is a "database" of (possibly versioned) snippets or, even better, a "knowledge base" or a "wiki" of snippets like github's gist.

If you are in my same position, most likely you are not allowed to publish your code. In this case, you have to setup your own gist, either on your PC or on a server on your LAN.

Have a look at gitpaste for this:

http://www.gitpaste.com/

https://github.com/justinvh/gitpaste

There are other gist clones that can be used for this task, out there. You can also use one of those "desktop wiki" (or "mind mapping") programs that were so fashionable some years ago.

Everything that can help you to create a small, managed (and possibly versioned) "snippet base" will work fine.

Of course, if you are allowed to publish your snippets, you can just use gist.


问:
Design pattern for isomorphic trees
I want to create a data structure to work with isomorphic tree. I don't search for a "algorithms" or methods to check if two or more trees are isomorphic each other. Just to create various trees with the same structure.

Example:

```<code>  2 - - - - - - - 'a' - - - - - - - 3.5
 / \              / \               / \
3   3           'f' 'y'           1.0 3.1
   / \              / \               / \
  4   7           'e' 'f'           2.3 7.7
</code>```

The first "layer" or tree is the "natural tree" (a tree with natural numbers), the second layer is the "character tree" and the third one is the "float tree".

The data structure has a method or iterator to traverse the tree and to make diferent operations with its values. These operations could change the value of nodes, but never its structure (first I create the structure and then I configure the tree with its diferent layers). In case of that I add a new node, this would be applied to each layer.

Which known design pattern fits with this description or is related with it?

答: If your trees are isomorphic on principle, there is no point at all in actually maintaining three parallel trees - that's just a waste of pointers and processor cycles. instead you should define a composite type that holds what ever items you want to maintain in parallel, and build one tree containing such composite nodes. Remember, how you access or present your data to other modules or users can be entirely independent from the actual data structure.

Title: Design pattern for isomorphic trees


问:
Why do operating systems do low level stuff in C and C++? Why not just C++?
On the Wikipedia page for Windows, it states the Windows is written in Assembly for the bootloader and task switcher, and C and C++ for kernel routines.

IIRC, you can call C++ functions from an extern "C"'d block. I can get using C for the kernel functions so pure C apps can use them (like printf and such), but if they can just be wrapped in an extern "C " block, then why code in C?

答:
Kernel developers are often the kind of people, who feel happier, when it is immediately evident from the source, what the code actually does.

C++ has many more features, which hide what the code does more than plain C code hides it: overloads, virtual methods, templates, references, throws... C++ also has vastly more syntax you have to master in order to even understand the C++ code using it.

I think power of C++ is very powerful tools to create libraries and frameworks, which then make application development a snap. Very often C++ application developer would be totally lost in the template-filled innards of a library, even when he is very competent at creating applications using that library. And writing a C++ library right is a very challenging programming task, and only done in order to provide a great framework for the benefit of application developer. C++ libraries are not internally simple, they are (or can be...) just powerful yet simple from application programmers point of view.

But kernel API can not be a C++ API, it must be a language-agnostic API, so most of the nice things in C++ would not be directly usable at that interface. Furthermore, kernel is not really divided into "library" and "application" parts developed independently, with more effort logically going to one library, to make creation of a mass of applications easy.

Also, security and stability is more critical inside a kernel, and virtual methods are much more dynamic and therefore much harder to isolate and verify, than plain callbacks or other C-like mechanisms.

In short, while you could of course write any C program including a kernel as C++, most of the power of C++ is not well used in kernel. And many would argue, that programming tools should prevent you from doing things you should not do. C++ would not.


答:
I think you're on the right track with revising the function names as you've suggested.  That will allow you to clarify the intent of what is happening as well as minimizing code duplication.

I would suggest calling processIntersections() something different though.  updateIntersections() or checkAndUpdateIntersections() would be two suggestions.  The intent is to get the function name closer to what is actually occurring.

I'm not sure I understand the concern over 'const-correctness'.  You said that workerIntersections would be a private method, so it's effectively hidden outside of that class.  If the concern is about providing a read-only guarantee to callers of checkIntersections(), then I would say that putting const on checkIntersections() is a nice-to-have, but isn't necessarily required.  If I had to pick between that guarantee versus minimizing duplicate code, then I'll go with less code.  Given that this is an internal API used by your firm, I wouldn't worry about the guarantee.

But that having been said...  If the guarantee is really important, then consider breaking the functionality of workerIntersections() apart.  What you've done so far is to put a facade in front of the original function in order to clarify intent.  In order to provide the const guarantee, you'll need to break the original function into a const checkOnly() function and a makeUpdates(int mode) function.

Whether or not you continue with the facade that you've suggested is really up to you.  Since you already have other callers providing a mode, you might want to keep the facade or it might be just as easy to refactor those at the same time you break apart the original function.

Title: share code between check and process methods

Body:
My job is to refactor an old library for GIS vector data processing. The main class encapsulates a collection of building outlines, and offers different methods for checking data consistency. Those checking functions have an optional parameter that allows to perform some process. For instance:

```<code>std::vector<Point> checkIntersections(int process_mode = 0);
</code>```

This method tests if some building outlines are intersecting, and return the intersection points. But if you pass a non null argument, the method will modify the outlines to remove the intersection.

I think it's pretty bad (at call site, a reader not familiar with the code base will assume that a method called checkSomething only performs a check and doesn't modifiy data) and I want to change this.
I also want to avoid code duplication as check and process methods are mostly similar.

So I was thinking to something like this:

```<code>// a private worker
std::vector<Point> workerIntersections(int process_mode = 0)
{
    // it's the equivalent of the current checkIntersections, it may perform
    // a process depending on process_mode
}

// public interfaces for check and process
std::vector<Point> checkIntersections()  /* const */
{
    workerIntersections(0);
}

std::vector<Point> processIntersections(int process_mode /*I have different process modes*/)
{
    workerIntersections(process_mode);
}
</code>```

But that forces me to break const correctness as workerIntersections is a non-const method.

How can I separate check and process, avoiding code duplication and keeping const-correctness?


问:
OO PHP static keyword, should I use it?
I'm writing script for fb and I have 3 objects that I'll be using through all classes. I'm wondering if there is any advantage in using the static keyword except I don't have to create an instance every time I need to use a method/object? Which way should I go, with static or without it?

I know this is basic, but I'm new to OOP and I want to learn to use it in a proper manner.

答:
I'm a bit confused by your question.
You have three objects: Instantiate them and pass them around by reference. You need three instances, use three instances, assuming that they are not modified do not need to be cloned etc. Alternatively check singleton pattern.

Static keyword: https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-java. It is exactly the same in PHP as in JAva snd elsewhere: you need it specific for the class, then it's static. Why has to do with maintenance, performance and other factors.

New to OOP: takes time, do not worry.

Title: OO PHP static keyword, should I use it?


问:
Instruction vs data cache usage
Say I've got a cache memory where instruction and data have different cache memories ("Harvard architecture"). Which cache, instruction or data, is used most often? I mean "most often" as in time, not amount of data since data memory might be used "more" in terms of amount of data while instruction cache might be used "more often" especially depending on the program.

Are there different answers a) in general and b) for a specific program?

答:
This is going to be entirely program specific. On the one hand, imagine a program that does nothing but a bunch of jumps around; which is exactly the size of the instruction cache. Zero data cache use, heaviest possible instruction cache use. Now imagine a program that does nothing but a bunch of memcpy operations everywhere. Minimal use of the instruction cache (assuming the memcpy gets pipelined); heaviest possible use of the data cache.

Of course, real software falls somewhere in the middle. But it still varies from program to program.

If recent CPU designs from the "Big Boys" are any indication, they typically use L1 caches of the same size for data and instruction caches; and have a large, shared, L2 cache (and occasionally an L3 cache).

Title: Instruction vs data cache usage