问:
Why is OOP difficult?
When I started using an object-oriented language (Java), I pretty much just went "Cool" and started coding. I've never really thought about it until only recently after having read lots of questions about OOP. The general impression I get is that people struggle with it. Since I haven't thought of it as hard, and I wouldn't say I'm any genius, I'm thinking that I must have missed something or misunderstood it.

Why is OOP difficult to understand? Is it difficult to understand?

答:
As someone who is currently learning programming and having some issues in this area, I don't think it is so much that the concept is difficult to understand as are the specific implementations of said concept.  I say this because I get the idea of OOP, and I've used it in PHP for about a year, but as I move on to C# and look at other programmers' usage of objects, I find that many people do so in ways that I just don't understand.  It is this specifically that has lead me down the road to finding a better understanding of the principles of OOP.

Of course, I realize that the issue is most likely my lack of experience with a natively-OOP language, and that as time goes by I will find new ways to utilize objects that will be just as unclear to a new programmer as what I am currently experiencing.  Jerry Coffin touches on this a few times, particularly in his comment:

This becomes especially problematic when on one hand you're told that
  a big advantage of OOP is modeling reality more closely, but you start
  off by taking what looks an awful lot like an LSD-inspired view of
  even the most basic and obvious parts of reality.

I find this to be very accurate, as it's the impression I often get when seeing someone creating classes for things that aren't really things - a specific example escapes me, but the closest I can come up with on the fly is treating distance like an object (I will edit the next time I see something that causes this same confusion).  At times, OOP seems to temporarily disregard its own rules and becomes less intuitive.  This more often than not occurs when objects are producing objects, inherit from a class that is encapsulating them, et cetera.

I think for someone like me, it helps to think of the concept of objects as having multiple facets, one of which includes treating something like an object when it otherwise wouldn't be.  Something like distance, with just a little paradigm shift, could come across as a theoretical object, but not one that could be held in your hand.  I have to think of it as having a set of properties but a more abstract set of behaviors, such as accessing its properties.  I'm not positive that this is the key to my understanding, but it seems to be where my current studies are leading.

Title: Why is OOP difficult?


问:
Why was the first compiler written before the first interpreter?
The first compiler was written by Grace Hopper in 1952 while the Lisp interpreter was written in 1958 by John McCarthy's student Steve Russell. Writing a compiler seems like a much harder problem than an interpreter. If that is so, why was the first compiler written six-years before the first interpreter?</p>

答:
Writing a compiler seems like a much harder problem than an interpreter.

That might be true today, but I would argue that it was not the case some 60 years ago. A few reasons why:

With an interpreter, you have to keep both it and the program in memory. In an age where 1kb of memory was a massive luxury, keeping the running memory footprint low was key. And interpreting requires a bit more memory than running a compiled program.

Modern CPUs are extremely complex with huge catalogs of instructions. So writing a good compiler is truly a challenge. Old CPUs were much simpler, so even compilation was simpler.

Modern languages are much more complex than old languages, so even compilers are much more complex. Old languages would thus have simpler compilers.

ContentLicense: CC BY-SA 3.0


问:
Pattern that prevents events to trigger themselves
I am working at the client-side part of a web application, that is responsible for getting answers from users for specific questions and storing and restoring them from the database (or cookies) and I am running into the issue that updating the answers from the db will also trigger saving them again (because the same method answerQuestion is called).

Here's a simplification of my use-case (coffeescript):

```<code>class Questionnaire
  constructor: ->
    @prefillAnswers()
    @listenToInput()
    @listenToQuestionChanges()

  prefillAnswers: ->
    for q in @questionNames
      @answerQuestion getAnswer(q)

  listenToInput: ->
    $('.input').on 'change', (e) =>
      $input = $(e.currentTarget)
      @answerQuestion $input.data('questionName'), $input.val()

  listenToQuestionChanges: ->
    @subscribeToEvent 'answeredQuestion', (msg, data) =>
      saveAnswer(data.question, data.answer)

  getAnswer: (qName) ->
    # fetches answer from a database (such as cookies, but is irrelevant)

  saveAnswer: (qName, answer) ->
    # saves the answer

  answerQuestion: (qName, answer) ->
    @publishEvent 'answeredQuestion', {question: qName, answer: answer} # This part triggers unnecessary saving, but where is the best place for this?
    # Change state of UI and data "model"
    # ...
</code>```

My question is, is there an OOP pattern that discusses this issue and possible solutions? I don't know how to start addressing this, and reading an entire book is not an option right now (I however have it on my todo list).

Perhaps this could be rewritten with a MVC pattern, and I'm moving towards that by starting to read the book JavaScript Web Applications, but can't see right now even with MVC, how my problem is avoided in the best way...

答:
The problem lies with the concept of answerQuestion.  You use answerQuestion for two roles:

User input provided, listeners perform appropriate actions.

Server update provided, listeners perform appropriate actions.

Simple approach

While they are similar, they are not the same.  The pattern for this (if you want to call it that), would be to have two separate methods.  The first method deals with triggering listeners, while the second should send the request to the server to save.

In this way, for scenario #1 when user provides input, you call not only the trigger method but also the save method (explicit call).  This way, when you receive a server update, you can simply call the trigger to update the page, without creating a second request.

Dirty flag

Another approach could be to use the concept of a dirty flag, which does nothing more than let your client know that it has changed with respect to the server's version.  Rather than use two separate methods, your answerQuestion will only perform the trigger.  A listener will check the dirty flag status, and if it has been changed, it will send update request to the server.  It should go without saying that all information coming from the server at that point will have its dirty flag set to false, and so even though your listener receives the event, it will see that no changes have been made and ignore it.

Event flags

Listeners should not generally care about the origin of the event in order to be truly decoupled, however you could provide event information in the form of a parameter in order to make a distinction based on who triggered it.  However, you may have to check multiple sources this way, so it may be preferable to simply use a boolean value indicating whether or not it is user input or triggered by the user in some way.  If another event is triggered as a consequence, that event too would maintain the same value for this flag since it too is (or is not) ultimately caused by a user.

Conclusion

While the dirty flag is better for larger projects, I wouldn't recommend it unless you find yourself having to repeat yourself several times for several different objects (thus becoming unreadable).  Event flags may fit you better if you prefer event-driven architecture rather than object-oriented like the dirty flag approach.

I hope that helps.


答:
If you are not holding everything in memory, compiled code is much more quick. Don't forget, that in these times functions were joined to the compiled code. If you are not compiling, you do not know what functions you'll need. So, you are calling functions from... Oh, not from disk yet, we are in early 50-ties, but from cards! In runtime! </p>

<p>Of course, it is possible to find a workarounds, but they were not found yet, for languages were very simple and  not so far from machine code. And compiling was easy and enough. </p>

Title: Why was the first compiler written before the first interpreter?

Body: The first compiler was written by Grace Hopper in 1952 while the Lisp interpreter was written in 1958 by John McCarthy's student Steve Russell. Writing a compiler seems like a much harder problem than an interpreter. If that is so, why was the first compiler written six-years before the first interpreter?</p>

Body:
If you are not holding everything in memory, compiled code is much more quick. Don't forget, that in these times functions were joined to the compiled code. If you are not compiling, you do not know what functions you'll need. So, you are calling functions from... Oh, not from disk yet, we are in early 50-ties, but from cards! In runtime!

Of course, it is possible to find a workarounds, but they were not found yet, for languages were very simple and  not so far from machine code. And compiling was easy and enough.


问:
does this model-pattern have a name?
A few years back, I wrote this answer to a question from which the following idea emerged.

I call these "Type Descriptors", as I have never been able to find this pattern documented or formally described anywhere - not to be confused with type descriptors in C#, but it's the most accurate name I've been able to come up with, so bear with me.

Here's my first attempt at a "formal" description:

A Type Descriptor is a type that provides meta-information about
  another type.

This pattern can be seen as an alternative to run-time reflection and
  annotations, and as such is equally applicable to languages that do or
  do not support reflection or annotations.

Type Descriptors are particularly useful as a means of describing
  aspects of model types found in for example domain and view-models, as
  well as in specialized types of models, such as form-models in a
  business- or web-application. Often such applications have many common
  aspects, such as the need to label inputs and perform common
  validations for e.g. required input, data types and formats, etc. -
  the information required by helper objects (or services) to handle
  these aspects fits comfortably in descriptors.

A descriptor mirrors the shape of the type it describes - for example,
  if a model type User has properties like id, name and email, it's type
  descriptor must have properties id, name and email, but where the
  properties on the model type have various value types (in this case
  for example integer and string) the properties of the descriptor are
  objects that provide information about those properties.

Maintaining identical model type and descriptor shapes may seem like
  duplication, in terms of property-names being identical in the model
  type and type descriptor - however, this does not violate the DRY
  principle as such, since the model type and descriptor, strictly
  speaking, are two different types that only happen to have the same
  shape, but do not have any overlapping concerns or duplication of any
  code; only the property names are duplicates.

I program mostly in PHP on a daily basis, and have used this pattern successfully to build applications. The following example is in PHP, though this could be implemented in any language capable of resolving properties by name at run-time.

A tiny bit of framework is required to implement this, so here goes...

A model-type implementing the following interface can provide a "type descriptor" - a type that describes the model-type itself:

```<code>interface TypeInfo
{
    function getType();
}
</code>```

Individual model-properties are described by "property descriptors" in the "type descriptor", for which I use a base class along the lines of this:

```<code>abstract class PropertyInfo
{
    /** @var string */
    public $name;

    /** @var string */
    public $label;

    public function __construct($name)
    {
        $this->name = $name;
    }
}
</code>```

From this class, I derive "property descriptors" for specific types of properties - for example, this type describes a string property:

```<code>class StringInfo extends PropertyInfo
{
    /**
     * @var int|null
     */
    public $max_length;
}
</code>```

Now here's a sample User model, and it's "type descriptor" UserType:

```<code>class User implements TypeInfo
{
    /** @var string */
    public $name;

    /** @var string */
    public $email;

    /** @return UserType */
    public function getType()
    {
        return UserType::instance();
    }
}

class UserType
{
    /** @var StringInfo */
    public $name;

    /** @var StringInfo */
    public $email;

    public function __construct()
    {
        $this->name = new StringInfo('name');
        $this->name->label = 'Full Name';
        $this->name->max_length = 50;

        $this->email = new StringInfo('email');
        $this->email->label = 'E-mail Address';
        $this->email->max_length = 128;
    }

    /** @return self */
    public static function instance()
    {
        static $instance;

        return $instance ?: $instance = new static();
    }
}
</code>```

As you can see, it's now possible to get the type descriptor either from a User instance by e.g. $user->getType() - notice that the property-names of the "property descriptors" in the "type descriptor" match the property-names in the actual model; using this pattern, it's my own responsibility to make sure the model and it's descriptor have the same shape.

Now I can write services and helpers etc. which may consume information from a "type descriptor" while working with model objects - for example, here's a very simple form helper:

```<code>class FormHelper
{
    /** @var TypeInfo */
    public $model;

    /** @var string */
    public $prefix;

    /**
     * @param TypeInfo $model
     * @param string     $prefix
     */
    public function __construct(TypeInfo $model, $prefix)
    {
        $this->model = $model;
        $this->prefix = $prefix;
    }

    /**
     * @param StringInfo $prop
     *
     * @return string
     */
    public function text(StringInfo $prop)
    {
        $name = $prop->name;

        return '<label for="' . $name . '">' . htmlspecialchars($prop->label) . '</label>'
            . '<input type="text" name="' . $this->prefix . '[' . $name . ']"'
            . ($prop->max_length ? ' maxlength="' . $prop->max_length . '"' : '')
            . ' value="' . $this->model->$name . '" id="' . $name . '" />';
    }
}
</code>```

You would use the form helper like this:

```<code>$user = new User;
$user->name = 'Rasmus';
$user->email = 'rschultz@gorges.us';

$form = new FormHelper($user, 'user');

$t = $user->getType();

echo $form->text($t->name) . "\n";
echo $form->text($t->email) . "\n";
</code>```

Which would output something like this:

```<code><label for="name">Full Name</label><input type="text" name="user[name]" maxlength="50" value="Rasmus" id="name" />
<label for="email">E-mail Address</label><input type="text" name="user[email]" maxlength="128" value="rschultz@gorges.us" id="email" />
</code>```

The two key reasons I enjoy working like this are (1) patterns like rendering forms, mapping post-data to model objects, mapping model-objects to database records, performing input validation and so forth can all be performed by formal helpers and service objects, all of which consume the same single source of information, and (2) everything is "statically typed", meaning only a single unchecked property-reference (by name, as a string) is made and encapsulated inside the "type descriptor", and type-hints and inference in a modern IDE (PhpStorm) can provide automated code inspections at development-time, I can safely use automated refactorings, and so forth.

Okay, a rather lengthy discourse, for what boils down to one question: does this pattern have a name? :-)

Side question: does this constitute (reflective) meta-programming? (The use of this pattern is very similar to e.g. using reflection to obtain annotations from a model, though I find this to be much safer, less complicated, more flexible and transparent.)

答:
That is an OOP Data Descriptor.  Although you are describing additional information about a class rather than information about bits in memory, the fundamental parity still applies;  you're describing in one place useful aspects about data in another place.

I'd advise you to adopt that name, write up a clearer definition of the pattern, and use the name in code.  ("Type" already means something in PHP, so you really shouldn't use it.)  So, your user class could be changed as follows:

```<code>class User {
   ...
   public function getDescriptor() {
   }
}

class UserDescriptor {
   ...
}
</code>```

Title: does this model-pattern have a name?

Body:
That is an OOP Data Descriptor.  Although you are describing additional information about a class rather than information about bits in memory, the fundamental parity still applies;  you're describing in one place useful aspects about data in another place.

I'd advise you to adopt that name, write up a clearer definition of the pattern, and use the name in code.  ("Type" already means something in PHP, so you really shouldn't use it.)  So, your user class could be changed as follows:

class User {
   ...
   public function getDescriptor() {
   }
}

class UserDescriptor {
   ...
}


问:
Efficiency of self-education
Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>

答:
I think we learn along with the job all the time.

I've learnt Struts, Spring and a host of other open source java frameworks and even using Tomcat by myself when I was working on Java/JSP projects. The company was not going to pay for this ;)

And now these are the technologies I use in my work daily.

ContentLicense: CC BY-SA 2.5

Title: Efficiency of self-education


问:
How to communicate side effects in a RESTful API on the server to the client?
I have been thinking a lot about Hypermedia REST-APIs for the last couple of weeks. One thing I am not quite sure about is how I want to model side effects on the server side.

In my current project, I am using JSON+HAL as the content-type, and am making use of links and embedded resources.

For example: Let's say some resource A gets PATCHed by the client, e.g. because a money value gets updated. Suppose this resource is used by another resource B. This resource B represents the sum of all resources that are of A's kind. Hence resource B would have provide a new value after A has been updated. What's the best way to communicate this to the client? The following options come to my mind:

Return all possibly updated links in the PATH response, i.e. especially a link to B. The client will then try to GET all provided links.

Embed those resources that may have been updated, and provide links to all other relevant resources.

Return a link to a parent resource of both A and B, because the whole state of A and B has been changed, and possibly even more.

Option 1) seems not right, because I may provide links to resources that are not really in the vicinity of A. Also, I cannot distinguish between resources that I should GET because they were updated, and resources that may be useful in other ways (for navigation, manipulating application state, creating new resources, ...)

Option 2) is basically the same as 1), but with the advantage that an embedded resource tells me directly the state of the resource, which is useful when I embed B.

Option 3) sounds the best to me so far. In this example I might have a parent resource "spreadsheet", which contains row resources, like A, and a sum resource, like B. If I change one of the rows, I get a link back to the spreadsheet, which the client can then GET, and either get all rows and sums embedded or as links.

Maybe I am missing some other options. I am really not sure what the best practice here is.

答:
So now I found out that you can actually signal changes in the link relation types. The RFC for link rels allows you to specify more than one link relation per link:

```<code>{
    _links : {
        "sum-of-rows has-changed" : { "href" : "http://..." },
        "some-other-link" : { "href" : "http://..." }
    }
    "value" : 5000.0
}
</code>```

In this case the has-change rel notifies the client that the resource behind that link has changed and should be refreshed.

Body:
So now I found out that you can actually signal changes in the link relation types. The RFC for link rels allows you to specify more than one link relation per link:

{
    _links : {
        "sum-of-rows has-changed" : { "href" : "http://..." },
        "some-other-link" : { "href" : "http://..." }
    }
    "value" : 5000.0
}

In this case the has-change rel notifies the client that the resource behind that link has changed and should be refreshed.


答:
Before the first compiler was written, people wrote assembler code which was a huge progress compared to plain binary code. At the time, there was a strong argument that code compiled by a compiler would be less efficient than assembler code - at that time the relation of (cost of computer) to (cost of programmer) was much, much different than today. So there was strong resistance against compilers from that point of view. </p>

<p>But compilers are an awful lot more efficient than interpreters. If you had suggested writing an interpreter at that point in time, people would have thought you are crazy. Can you imagine buying a million dollar computer and then wasting 90% of its power to interpret code? </p>

Body:
Before the first compiler was written, people wrote assembler code which was a huge progress compared to plain binary code. At the time, there was a strong argument that code compiled by a compiler would be less efficient than assembler code - at that time the relation of (cost of computer) to (cost of programmer) was much, much different than today. So there was strong resistance against compilers from that point of view.

But compilers are an awful lot more efficient than interpreters. If you had suggested writing an interpreter at that point in time, people would have thought you are crazy. Can you imagine buying a million dollar computer and then wasting 90% of its power to interpret code?


问:
Changing an int to be a string in PHP / MySQL Schema

Background

I'm trying to decide the best way to manage a change in requirements.
Currently when an admin is assigned to a ticket, the ticket header record is given an owner and the ownerID field is updated with the value of the id which corresponds to the record in the TeamMembers table. The owner (Team member) is notified when a user (Customer) updates the ticket with a comment. I now need to add additional Team Members to the ticket so they are also notified.

Question ?

Do I...

Make ownerID field ownerIDs and store a comma separated list of IDs in a string ?

Add a new field additionalOwnerIDs and store any extra IDs after the main owner as a comma separated string ?

Create a new table that simply links ticketID to assigned owners and have one row per owner ?

Do something else ?

Considerations

I want to deliver the new functionality as quickly as possible, repurposing the existing field might seem like the simplest way forward but it would involve changing the schema type of existing data so will need a migration script to rewrite hundreds of thousands of rows.

Adding a new field then wouldn't need as much migration work as it would be an empty string for all existing records and default to an empty string for new records.

A new link table seems the most programatically correct way (IMHO) but would require the most time to implement and test it and the migrations would be the most complicated in terms of extracting existing ticket owners into the new table. Changing the code for retrieving / updating an owner to query the new table. Then removing the defunct ownerID column from the existing table.

Have a missed anything? Which approach is the best in terms of maintaining the code base in the future?

答: Go with option #3, creating a new table.  Embedding CSV data in columns is just going to be a headache down the road for you because you'll have data that is not easily retrievable.  In this case, if you embedded a CSV list of users, it would prevent you from easily searching on tickets that a user is assigned with a single SQL statement.</p>


答:
You've definitely thought this problem out well.  I agree with you that option three is the best practice; I would choose that option.  Creating a new table that links many owner IDs to a single ticket ID makes the most sense to me.  It is intuitive and will make the database more maintainable in the future.

Some considerations for option 3:

Your going to have to update how an owner is linked to a ticket.  My suggestions is to update the GUI to use a control like this one: http://diminishing.org/assets/combo_select.png

Your going to have to deprecate the existing creation, update and retrieval of owners and update it to create, update and retrieve from your newly created table.  Depending on the info you want to return you may have to join the Owner and Ticket table.

There is now more than one owner per ticket.  It's very likely that there is existing functionality that depends on having a single owner.  Your going to have to scout that functionality and return to your clients with a recommendation on solving those problems.

This may sound like a lot of work initially.  However, I believe that it will be the easiest to extend functionality later on.  It will also be less of a learning curve for future developers.

Problems with comma separated options:

Your not letting the database do its job.  The database is there to perform retrievals, updates and creations; it is optimized to do these things.  Storing data as a string means you need to write code to parse it and perform operations that the database should be performing.

It's hard to see connections between tables.  Your simulating a relationship in code.  It will be hard to see the relationship at first glance if there are a ton of entries in your comma delimited field.  This contributes to a steep learning curve for new developers and a headache if you need to debug later.

You will have to debug your database relationships through your code instead of writing queries.  You want to be able to run your software and execute a SQL query to see if the relationship was setup properly in tables.  However, with comma delimited you will need to debug this relationship through code instead of running a simple SQL query.  This is a time waster and a pain.

I'm sure there are more reasons not to use comma delimited fields in a database.  That's a few to help understand why it's not a good idea.  I'm sure people could come up with advantages for storing comma delimited fields as well.  However, it is my opinion that it is bad practice to store comma delimited fields in a database.

Title: Changing an int to be a string in PHP / MySQL Schema

Body:
Background

I'm trying to decide the best way to manage a change in requirements.
Currently when an admin is assigned to a ticket, the ticket header record is given an owner and the ownerID field is updated with the value of the id which corresponds to the record in the TeamMembers table. The owner (Team member) is notified when a user (Customer) updates the ticket with a comment. I now need to add additional Team Members to the ticket so they are also notified.

Question ?

Do I...

Make ownerID field ownerIDs and store a comma separated list of IDs in a string ?

Add a new field additionalOwnerIDs and store any extra IDs after the main owner as a comma separated string ?

Create a new table that simply links ticketID to assigned owners and have one row per owner ?

Do something else ?

Considerations

I want to deliver the new functionality as quickly as possible, repurposing the existing field might seem like the simplest way forward but it would involve changing the schema type of existing data so will need a migration script to rewrite hundreds of thousands of rows.

Adding a new field then wouldn't need as much migration work as it would be an empty string for all existing records and default to an empty string for new records.

A new link table seems the most programatically correct way (IMHO) but would require the most time to implement and test it and the migrations would be the most complicated in terms of extracting existing ticket owners into the new table. Changing the code for retrieving / updating an owner to query the new table. Then removing the defunct ownerID column from the existing table.

Have a missed anything? Which approach is the best in terms of maintaining the code base in the future?


答:
Generally the more you know the more self learning becomes the only efficient way to teach yourself things.

Courses are great when you're just starting out as a kick start but after that you get a diminishing return for days sitting in a classroom as the course moves at the pace of the slowest participant.  Once you've got a reasonable level of experience that's almost never you so you're always going to be wasting time.

Self study on the other hand allows you to pace yourself.  If you get something quickly you can skim along, if you don't understand it go back and go over it again.  If you think a topic is irrelevant you can ignore it.

What I've taught myself?  In terms of things I've learned from scratch: HTML, ASP, VB.NET, JavaScript, LotusScript, a bit of Python, a bit of Java.

But in reality almost everything useful is self taught on the job.  You may learn the basics on a course but where you really learn it is using it so I'd say 95% of what I know (if not more) is self taught.

Title: Efficiency of self-education

Body: Do you think being self-educated in software development is good? Please give an example of what you have learnt successfully by yourself.</p>


答:
The fundamental point is that the computing hardware environment of the 1950s made it such that only a compiler was feasible given the batch-oriented processing of computers back then.

At the time the better user interfaces were primarily limited to punch cards and teletype printers. In 1961 the SAGE system became the first Cathode-Ray Tube (CRT) display on a computer. So the interactive nature of an interpreter was not preferable or natural until much later.

Numerous computers in the 1950s used front panel switches to load instructions, and the output was simply rows of lamps/LEDs, and hobbyists even used front-panel switches & LEDs into the 1970s. Maybe you're familiar with the infamous Altair 8800.

Other hardware limitations also made interpreters unfeasible. There was the extreme limited availability of primary memory (e.g. RAM) in computers in the 1950s. Prior to the semiconductor integrated circuit (which didn't come until 1958) memory was limited to magnetic core memory or delay line memory which was measured in bits or words, no prefix. Combined with the slowness of secondary storage memory (e.g. disk or tape), it would be considered wasteful, if not unfeasible to have much of the memory used for the interpreter, even before the program being interpreted was loaded.

Memory limitations were still a major factor when the team lead by John Backus at IBM created the FORTRAN compiler in 1954-57. This innovative compiler was successful only because it was an optimizing compiler.

Most of the computers in the 1950s barely had any Operating System, let alone modern features such as dynamic linking and virtual memory management, so the idea of an interpreter was too radical and impractical at that time.

Addendum

The languages of the 1950s were primitive. They included only a small handful of operations, often influenced either by the underlying hardware's instructions or the problem definition of their targeted use.

At that time, computers were rarely general purpose computers in the sense that we think of computers today. That they were reprogrammable without having to be rebuilt was considered a revolutionary concept  -- previously people had been using electromechanical  machines (typically calculators) to compute or calculate answers (the majority of applications in the 1950s were numeric in nature).

From a Computer Science point of view, compilers and interpreters are both translators, and roughly equal in complexity to implement.


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

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

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

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

                    [settingID] => 3
                )

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

        )

)
</code>```

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

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

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

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

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

答:
This seems like the perfect application of the strategy pattern.  The basic idea is that you have a bunch of different strategies (these are database connection settings in you scenario) and based on a condition (this is the locale in your scenario) you execute a specific strategy.

The best example I've seen to describe this pattern has to do with a checkout application that needs to calculate tax based on your country of origin.  There are lots of ways to implement this.  The example below uses an if statement based on your country.  If you needed to support 2 or 3 countries, then this would suffice.  If you needed to support 20 countries, then you would want to put the logic into different objects.

```<code>class TaxStrategy {
    public double CalculateTaxByCountry(String country, double amount) {
       if (country equals "Canada") {
           return 0.12 * amount;
       }
       else if (country equals ("USA")) {
           return 0.05 * amount;
       }
    }
}

class Main {
    public static void main(String[] args) {
        TaxStrategy taxStrategy = new TaxStrategy();
        String countryOfOrigin = "Canada"; // you would get this from the user
        double amount = 15.84;
        double tax = taxStrategy.CalculateTaxByCountry(countryOfOrigin);
    }
}
</code>```

More information on this pattern can be found here: http://www.oodesign.com/strategy-pattern.html  There is an example in this link that shows how to implement it with classes.  The example I provided shows the basic idea of how the pattern works on its simplest level.

Body:
This seems like the perfect application of the strategy pattern.  The basic idea is that you have a bunch of different strategies (these are database connection settings in you scenario) and based on a condition (this is the locale in your scenario) you execute a specific strategy.

The best example I've seen to describe this pattern has to do with a checkout application that needs to calculate tax based on your country of origin.  There are lots of ways to implement this.  The example below uses an if statement based on your country.  If you needed to support 2 or 3 countries, then this would suffice.  If you needed to support 20 countries, then you would want to put the logic into different objects.

class TaxStrategy {
    public double CalculateTaxByCountry(String country, double amount) {
       if (country equals "Canada") {
           return 0.12 * amount;
       }
       else if (country equals ("USA")) {
           return 0.05 * amount;
       }
    }
}

class Main {
    public static void main(String[] args) {
        TaxStrategy taxStrategy = new TaxStrategy();
        String countryOfOrigin = "Canada"; // you would get this from the user
        double amount = 15.84;
        double tax = taxStrategy.CalculateTaxByCountry(countryOfOrigin);
    }
}

More information on this pattern can be found here: http://www.oodesign.com/strategy-pattern.html  There is an example in this link that shows how to implement it with classes.  The example I provided shows the basic idea of how the pattern works on its simplest level.


问:
I made improvements to free code I found online and notified the author. Was this the right thing to do?
I recently used a library from http://www.braemoor.co.uk/software/index.shtml (the EU VAT No validation library at http://www.braemoor.co.uk/software/vat.shtml) in a project at work. It mentions as the license (or something that looks like one):

All software is provided as freeware for personal or commercial use without obligation by either party. The author will not accept responsibility for any problems that may be incurred by use of this software, although any errors reported will be corrected as soon as possible. Re-distribution of this software is NOT permitted without explicit permission.

I checked the code and found (and applied) a few ways to improve the code so it's more easily maintainable and more readable (you can find one of them on CodeReview.SE). After applying these changes, I considered that others might benefit from them as well and sent them as feedback to the author on his contact address. A few hours later, the author sent a reply thanking me for my suggestions, and that he would go over my changes and keep me informed.

My main concern is that while the website mentioned that it was freeware, I'm not sure how far I am allowed to go in altering his software without knowing the license. I assume it's license-free, but it's not specifically mentioned as open source, and I'm slightly worried that I might have overstepped my bounds and took too much liberty with the whole thing.

Did I do the right thing?

答:
Legally, you're almost certainly fine (assuming the changes you offered are yours to offer).  The author provided the source, and shouldn't be surprised if people use it and/or improve on it.  The only reasonable restriction would be on distribution, and even that is probably not an issue in your case.  (But ask the author before you host the code somewhere, for example).

Ethically, in my opinion, there's nothing wrong with offering improvements to someone's code, as long as:

they're within the project's intended scope;

they work exactly as advertised (or as close to it as at all possible); and

their addition to the project wouldn't subject anyone to any hidden or onerous license terms, or make the project incompatible with its own license.

If the change fixes bugs or improves maintainability without changing functionality, you definitely did the right thing.


答:
There are several aspects to self learning, the first of course being independent study where you seek knowledge and begin putting it to practical use. This could mean buying some books, studying open source code, experimenting until the wee hours of the morning or (usually) all of the above.

At some point, however, you are going to need one or several mentors to guide you through caveats, tough topics, best practices and solid engineering principles. An efficient self learner will seek these mentors much sooner than later, and get his/her code in front of as many highly experienced people as possible.

I learned BASIC, Pascal, C, PHP, rudimentary x86 assembly without taking classes, but that doesn't mean that I did not have a teacher to call upon when I needed one. So, given the fact that I learned a considerable amount from mentors that I found in the free/open source community .. I'd be hard pressed to say that I learned anything on my own or by myself.

This method of learning is the only method that works for me, reaching far beyond the study of programming.

Title: Efficiency of self-education


答:
The first programming languages were quite simple (no recursion for
example) and close to machine architecture which was itself
simple. The translation was then a straightforward process.

A compiler was simpler as a program than an interpreter that
would have to keep together both the data for program execution and
the tables to interpret the source code. And the interpreter would
take more space, for itself, for program source code and for symbolic
tables.

Memory could be so scarce (for both cost and architectural reasons)
that compilers could be stand-alone programs that overwrote the
operating system (I did use one of these). The OS had to be reloaded
after compiling in order to run the compiled program. ... which does
make it clear that running an interpreter for real work was simply not an option.

To be true, the simplicity required of compilers was such that
compilers were not very good (code optimization was still in infancy, when considered at all). Hand written machine code had, at least
until the late sixties in some places, the reputation of being
significantly more efficient than compiler generated code. There was even a concept of code expansion ratio, that compared the size
of compiled code to the work of a very good programmer. It was usually
greater than 1 for most (all?) compilers, which meant slower programs, and,
much more importantly, larger programs requiring more memory. This was
still an issue in the sixties.

The interest of compiler was in programming ease, especially for users
who were not computing specialists, such as scientists in various
fields. This interest was not code performance. But still, programmer
time was then considered a cheap resource. The cost was in computer
time, until 1975-1980, when the cost switched from hardware to
software. Which means that even compiler were not taken seriously by
some professionals.

The very high cost of computer time was yet another reason for
disqualifying interpreters, to the point that the very idea would have
been laughable for most people.

The case of Lisp is very special, because it was an extremely simple
language which made it feasable (and the computer had become a bit
bigger in 58). More importantly, the Lisp interpreter was a proof of
concept regarding the self definability of Lisp (meta-circularity), independently of any
issue of usability.

Lisp success is due largely to the fact that this self definibility made it an
excellent testbed for studying programming structures and design new
languages (and also for its convenience for symbolic computation).


问:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.

答:
Think in your users/client point of view. A software system is a collection of features that gives this users/clients some value. Of course each one of this features have and UI, a backend and some other things.

Build your system always feature by feature, and try divide in very small features. This way you are always near to have something more to deliver to your customers, remember that software development its not about build the version 1.0 its about going to the version 1.0.1 to the 1.0.2 and so on...


答:
Before a looping program can be interpreted, it must be stored in a medium which can be read repeatedly.  In most cases, the only suitable medium would be RAM.  Since code will typically be entered on punched cards which--for human readable languages--are likely to be largely empty, some sort of processing must be performed upon the code before it is stored in RAM.  In many cases, processing the punched-card text into a form which is suitable for direct execution by the processor is not really any more difficult than processing it into a form which could be efficiently handled via an interpreter.

Note that the goal of the early compilers was not to produce an assembly-language or object-code file on disk, but rather to end up code in RAM that was ready to execute.  This is actually surprisingly easy when there's no operating system to get in the way.  A compiler can generate code starting at one end of memory and allocate variables and branch targets starting at the other.  If a statement is marked with label "1234", the compiler will store in variable called "1234" an instruction to jump to the current code generation address, creating that variable if it doesn't exist.  A statement "goto 1234" will create a variable "1234" if it doesn't exist, and then jump to that variable [which will hopefully have a jump to the proper location stored in it before that statement executes].  Note that the compiler doesn't have to do anything special to allow code to goto a label which hasn't been defined yet, since it knows when the goto compiles where it's going to jump--to a variable.  That may not be the most efficient way to generate code, but it's adequate for the sizes of programs that computers were expected to handle.


问:
What is the ideal length of a method for you?
In object-oriented programming, there is of course no exact rule on the maximum length of a method , but I still found these two quotes somewhat contradicting each other, so I would like to hear what you think.

In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

The first rule of functions is that they should be small. The second
  rule of functions is that they should be smaller than that. Functions
  should not be 100 lines long. Functions should hardly ever be 20 lines
  long.

and he gives an example from Java code he sees from Kent Beck:

Every function in his program was just two, or three, or four lines
  long. Each was transparently obvious. Each told a story. And each led
  you to the next in a compelling order. That’s how short your functions
  should be!

This sounds great, but on the other hand, in Code Complete, Steve McConnell says something very different:

The routine should be allowed to grow organically up to 100-200 lines,
  decades of evidence say that routines of such length no more error
  prone then shorter routines.

And he gives a reference to a study that says routines 65 lines or long are cheaper to develop.

So while there are diverging opinions about the matter, is there a functional best-practice for you?

答:
I've been in this crazy racket, one way or another, since 1970.

In all that time, with two exceptions that I'll get to in a moment, I have NEVER seen a well-designed "routine" (method, procedure, function, subroutine, whatever) that NEEDED to be more than one printed page (about 60 lines) long.  The vast majority of them were quite a bit short, on the order of 10-20 lines.

I have, however, seen a LOT of "stream-of-consciousness" code, written by people who apparently never heard of modularization.

The two exceptions were very much special cases.  One is actually a class of exception cases, that I lump together: large finite-state automata, implemented as big ugly switch statements, usually because there isn't a cleaner way to implement them.  These things usually show up in automated test equipment, parsing data logs from the device under test.

The other was the photon torpedo routine from the Matuszek-Reynolds-McGehearty-Cohen STARTRK game, written in CDC 6600 FORTRAN IV.  It had to parse the command line, then simulate the flight of each torpedo, with perturbations, check the interaction between the torpedo and each kind of thing it could hit, and oh by the way simulate recursion to do 8-way connectivity on chains of novae from torpedoing a star that was next to other stars.

OwnerDisplayName: iPhoneDeveloper


问:
Why are there so many CSS properties which are essentially the same?
This answer really made me wonder.

I've written CSS before and (usually) I don't really bother to support browsers other than recent firefox and chrome, but in researching I've noticed that, for the exact same CSS property, there are usually at least three different forms which behave identically, and can have the same values, but which all simply have different prefixes for the specific library that implements them.

Here, for example:

```<code>-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
</code>```

With the sole exception of the first one, these only differ by prefix. Why don't maintainers simply change the lexer rule which matches the string "-moz-user-select" to also match "user-select"? Sure, there's the possibility that the author of the original CSS wanted different behavior for Firefox v. other browsers, so "user-select" won't be the same as "-moz-user-select", but the risk of that weird corner case is far outweighed by the advantage, and there are other, arguably better ways to accomplish the browser-specific goal.

If this is already occurring, why do people still use all of these? If they stopped:

there would be fewer bits clogging the metaphorical pipes of the internet (network latency would go way down, plus individual pages would load faster), and

people using ancient browsers would be given the impetus they need to update (which they should do for security reasons, anyway)

TL;DR

What would the disadvantage be of everyone using the same naming convention? Why haven't things normalized by now?

答:
Most of these are due to vendor prefixes.

A new standard that has not been finalized may get implemented in a browser, but since it has not been finalized, the browser vendor (creator) will not want to use the "official" correct attribute, but they still want to support the feature.

So they add a prefix - -webkit-*, -moz-*, -khtml- and -ms-* are specific to the different browsers/rendering engines.

And as a developer, while browsers gain support but don't yet use the "official" name, you may want to support the feature - so you add the vendor prefixes and the official one for future proofing.

Sometimes a feature changes name during the standardization process, so you end up with a vendor prefix using a different name, or having two different names for the same feature (normally in different browser versions of the same rendering engine).

Why haven't things normalized by now?

New standards are being worked on and getting finalized all the time. Different vendors have different priorities on which vendors they want to support. So - a moving target + different priorities, gives you... vendor prefixes and no single standard name at one point in time.


问:
Encapsulation: Separate functions for separate variables, or return a table? [PHP]
I have been making a website with PHP and I have a few classes, so far none of them really follow encapsulation rules of OOP. Lets say I have a user class like so:

```<code>class User{
    public $username;
    public $uid;
    public $date;
    public $location;
    public $bio;
    public $avatar;
    public function __construct($user, $uidOr){
        $this->username = $user;
        $this->uidOr = $uidOr;
    } .

    public function getUser(){
        if($this->uidOr){
            $which = "uid";
        } else { $which = "username"; }
// /\ I know the above is bad
        $getUserInfoQuery = new Database();
        $getUserInfoQuery->fetchAll("users", array($which, $this->username));

        foreach ($getUserInfoQuery->result as $value) {
            $this->username = $value['username'];
            $this->uid = $value['uid'];
            $this->date = $value['date'];
            $this->location = $value['location'];
            $this->bio = $value['bio'];
            $this->avatar = $value['avatarurl'];
        }
    }
}
</code>```

That obviously is terrible practise of OOP, right? Should I be adding functions like getUserUsername(); which return the username of the user object or should I make a function which returns a table of information. What would be best?
Thanks! PS: sorry for my bad code, im new to OOP.

答:
Your right that a big part of OOP is encapsulation.  You run the risk of any code being able to modify your instance variables when you declare them all as public.  Using public variables also encourages you to not encapsulate your business logic.  Anyway, your not interested in why it's bad to declare public instance variables.

The simple answer to your question is yes it's bad practice to declare public variables.  You should declare your variables as private and return them on an as needed basis.  If you need access to a variable, then access it.  If you want to return a bunch of information at once, then return the object containing the information.  The whole point of that object is to contain the information you need.  Returning all the info defeats the purpose of having an object.

It's common to use properties to represent instance variables in a domain object.  A property can be read only or not based on its usage.  Here's an example of your code written using properties.

```<code>class User {
    private String username;

    public String Username() {
        return username;
    }

    public void Username(String value) {
        username = value;
    }
}
</code>```

If you want to make an instance variable read only, then omit the setter.  If you don't want a variable to be readable at all, then don't include a getter and setter.  People also refer to these are mutators and accessors.

Here's an example of PHP mutator and accessors being used.  This link also provides PHP specific syntax that includes shortcuts.  Shortcuts are nice because they clean up your code and they are universally understood.

http://www.refulz.com/mutator-and-accessor-methods-in-php/

Body:
Your right that a big part of OOP is encapsulation.  You run the risk of any code being able to modify your instance variables when you declare them all as public.  Using public variables also encourages you to not encapsulate your business logic.  Anyway, your not interested in why it's bad to declare public instance variables.

The simple answer to your question is yes it's bad practice to declare public variables.  You should declare your variables as private and return them on an as needed basis.  If you need access to a variable, then access it.  If you want to return a bunch of information at once, then return the object containing the information.  The whole point of that object is to contain the information you need.  Returning all the info defeats the purpose of having an object.

It's common to use properties to represent instance variables in a domain object.  A property can be read only or not based on its usage.  Here's an example of your code written using properties.

class User {
    private String username;

    public String Username() {
        return username;
    }

    public void Username(String value) {
        username = value;
    }
}

If you want to make an instance variable read only, then omit the setter.  If you don't want a variable to be readable at all, then don't include a getter and setter.  People also refer to these are mutators and accessors.

Here's an example of PHP mutator and accessors being used.  This link also provides PHP specific syntax that includes shortcuts.  Shortcuts are nice because they clean up your code and they are universally understood.

http://www.refulz.com/mutator-and-accessor-methods-in-php/


问:
What is a lambda, and why would it be useful?
So far I heard about :

Lambda calculus

Lambda programming

Lambda expressions

Lambda functions

Which all seems to be related to functional programming...

Apparently it will be integrated into C++1x, so I might better understand it now:

http://en.wikipedia.org/wiki/C%2B%2B0x#Lambda_functions_and_expressions

Can somebody defines briefly what are lambdas things and give an where it can be useful ?

答:
Basically, lambda functions are functions you create "on the fly". In C++1x they could be used to improve on its support for functional programming:

```<code>std::for_each( begin, end, [](int i){std::cout << i << '\n';} );
</code>```

This will roughly result in code similar to this one:

```<code>struct some_functor {
  void operator()(int i) {std::cout << i << '\n';}
};

std::for_each( begin, end, some_functor() );
</code>```

If you need some_functor just for this one call to std::for_each(), then that lambda function has several advantages over it:

what's done in the loop is specified right where the looping function is called

it relieves you from writing some of the boiler-plate code

there's no functor lying around at some namespace scope that makes everyone looking at the code wondering what it is needed for

Body:
Basically, lambda functions are functions you create "on the fly". In C++1x they could be used to improve on its support for functional programming:

std::for_each( begin, end, [](int i){std::cout << i << '\n';} );

This will roughly result in code similar to this one:

struct some_functor {
  void operator()(int i) {std::cout << i << '\n';}
};

std::for_each( begin, end, some_functor() );

If you need some_functor just for this one call to std::for_each(), then that lambda function has several advantages over it:

what's done in the loop is specified right where the looping function is called

it relieves you from writing some of the boiler-plate code

there's no functor lying around at some namespace scope that makes everyone looking at the code wondering what it is needed for


答:
Your getUser function would probably be better named populateFromDB, or maybe initFromDB. If the function name is getUser, I expect a User object to be returned. What happens here is some members are populated but as far as I can tell nothing is actually returned.

Having separate getters and setters for private members, where necessary, is a common practice. If you really don't think you'll ever need that you can instead have a single function named getUserFields which could return an array containing all of the different fields.

In your example, you've completely broken encapsulation by making everything public. So you might also want to make all the members private and then add whatever getter/setter functions are necessary (or a single function that returns everything in an array).

Title: Encapsulation: Separate functions for separate variables, or return a table? [PHP]

Body:
I have been making a website with PHP and I have a few classes, so far none of them really follow encapsulation rules of OOP. Lets say I have a user class like so:

```<code>class User{
    public $username;
    public $uid;
    public $date;
    public $location;
    public $bio;
    public $avatar;
    public function __construct($user, $uidOr){
        $this->username = $user;
        $this->uidOr = $uidOr;
    } .

    public function getUser(){
        if($this->uidOr){
            $which = "uid";
        } else { $which = "username"; }
// /\ I know the above is bad
        $getUserInfoQuery = new Database();
        $getUserInfoQuery->fetchAll("users", array($which, $this->username));

        foreach ($getUserInfoQuery->result as $value) {
            $this->username = $value['username'];
            $this->uid = $value['uid'];
            $this->date = $value['date'];
            $this->location = $value['location'];
            $this->bio = $value['bio'];
            $this->avatar = $value['avatarurl'];
        }
    }
}
</code>```

That obviously is terrible practise of OOP, right? Should I be adding functions like getUserUsername(); which return the username of the user object or should I make a function which returns a table of information. What would be best?
Thanks! PS: sorry for my bad code, im new to OOP.


问:
In general, should an organization adopt a single methodology or decide on a per-project basis?
I work for a company that, in my opinion, should be doing all of it's web development work in a fully agile manner. We have vague, competing ideas about the product at any given time. And we have strict deadlines. So, in the web arena it seems to make sense to operate in as agile a manner as possible.

However, I could conceive of projects on the business apps side -- or even a complex sub-project on the web side (integrating with a pre-existent 3rd party app?) that, at least for the sake of argument, isn't at all changeable in scope. The scope of the integration piece would, for all intents and purposes, be fully specifiable up-front with zero chance for change.

In general, is it acceptable to take project X in an organization that is normally attempting to achieve agility and work through it in a waterfall manner? Does it somehow compromise the agility of the organization on a whole? If the organization is truly trying to be agile, should the "rigid" project still be "managed" in an agile manner?

答:
I don't see the benefit of trying to do everything the same unless you're willing to turn-down projects that don't fit your particular model. Otherwise, you get a bad fit and the client isn't going to be happy either way.

If you're so sure you know the specs in one case and are very confident they won't change, you can still run it as an agile project. Just because Agile is better when specs are vague, doesn't mean it is useless when they are solid.

Keep things as consistent as possible so you can have members work on different projects without too much adaptation of the general method. People are better at making adaptations when they fully understand what it is they are adapting; otherwise, it's just chaos. Of course, this assumes all your clients are willing to work under an agile methodology.


问:
How do VMs implement function calling?
I'm reading a compiler textbook that compiles to some form of assembly. Since I don't know this assembly language I decided to invent my own simple "assembly language"  and implement a basic "virtual machine" which will execute these instructions.

Currently I'm thinking how I can implement function decleration and function calling in the language and VM.

I had the following idea, please tell me what you think:

Function declerations would look like simple labels. At the end of a function there's an end statement. The 'main program' is a function by itself. For examle:

```<code>main:
// some logic
CALL funcA
// more logic
END
funcA:
// .. some logic
END
</code>```

However the difference between call <function> and goto  is this:

goto simply sets the 'instruction pointer' (the register that holds the number of the next line to be executed) to the line number of the label.

call does what goto does, but before jumping it pushes the current line number (plus 1) onto a stack.

When end is reached, the VM pops the top of the stack and jumps to this line number. If there is nothing in the stack, the program terminates.

So for example, for the code above this is what happens:

```<code>main: // this is where the VM starts
// some logic
CALL funcA // push onto the stack the number 4 (3+1), and jump to the label funcA
// more logic .. this is where we return to from funcA
END // pop the top of the stack and jump to this line number. nothing -> terminate
funcA:
// .. some logic
END // pop the top of the stack (the number 4), and jump to this line number
</code>```

What do you think of this approach?

答:
It depends on the VM, to be honest.

It is a bit easier to write a VM in an OO language that operates on data structures kept in memory rather than on some form of linearized bytecode.  If you ever implement a toy programming language you might decide to do it this way, at least initially (I have done this before), in which case the VM is probably just a polymorphic "run()" method.  A lot of scripting languages work this way, because the code will be generated at the same time in which it is run, so there is no need to maintain the bytecode for later.

If you compile all the way to a linearized bytecode (like how Java compiles), the way you handle operation calls will depend on the language.  If you do not allow recursion (most old programming languages originally did not), you can simply inline the operation calls directly into the bytecode.  This causes code bloat but is "safe" otherwise.

If you compile all the way to a linearized bytecode, but you want to allow recursion, then you'll need to emulate a call stack.  Each frame of the stack will hold a reference to the location in the code segment where that operation was invoked (for operation-based frames).  It will also hold copies of all variables local to that frame.  Objects to which those variables refer may be held on the stack or in a separate heap segment, depending on the design of the programming language and (more likely) the code optimizer being used by the compiler.

Title: How do VMs implement function calling?


答:
Self-education is not just good, but essential if you want to be an above-average developer.

The only person responsible for your professional progress is you. Sure, formal education, training courses, etc. can help, but at the end of the day, it is your career.

I'm fortunate enough to have benefitted from a very good education, and I have had good employers who have supported my learning in all sorts of different ways. However, the vast majority of what I have learned about programming I have picked up myself - by reading lots and practicing more.

Title: Efficiency of self-education


答:
Agile vs Waterfall its not only about have a set requirements up front. There are other agile values aside from responding to change, for example:

People more important than process.

Deploy software that works in short iterations.

If your company is agile i cannot see how you can abandon this agility for one project, agile its much more about a mindset and core values than about concrete practiques. If for a project do you have solid requirements that don't change you can still work on this projects with your agile values and mindset. Go in small iterations, empower your team, show software that works frequently... with agile you are prepared to change, if change don't appears you are off course prepared to this too.

Title: In general, should an organization adopt a single methodology or decide on a per-project basis?

Body:
I work for a company that, in my opinion, should be doing all of it's web development work in a fully agile manner. We have vague, competing ideas about the product at any given time. And we have strict deadlines. So, in the web arena it seems to make sense to operate in as agile a manner as possible.

However, I could conceive of projects on the business apps side -- or even a complex sub-project on the web side (integrating with a pre-existent 3rd party app?) that, at least for the sake of argument, isn't at all changeable in scope. The scope of the integration piece would, for all intents and purposes, be fully specifiable up-front with zero chance for change.

In general, is it acceptable to take project X in an organization that is normally attempting to achieve agility and work through it in a waterfall manner? Does it somehow compromise the agility of the organization on a whole? If the organization is truly trying to be agile, should the "rigid" project still be "managed" in an agile manner?


答:
Do the authors mean the same thing by "function" and "routine"?  Typically when I say "function" I mean a subroutine/operation which returns a value and "procedure" for one which does not (and whose call becomes a single statement).  This is not a common distinction throughout SE in the real world but I have seen it in user texts.

Either way, there is no right answer to this.  Preference for one or the other (if there is a preference at all) is something I would expect to be very different between languages, projects, and organizations; just as it is with all code conventions.

The one bit I would add is that the whole "long operations are no more error-prone than short operations" assertion is not strictly true.  In addition to the fact that more code equals more potential error space, it is blindingly obvious that breaking code into segments will make errors both easier to avoid and easier to locate.  Otherwise there would be no reason to break code into pieces at all, save repetition.  But this is perhaps true only if said segments are documented well enough that you can determine the results of an operation call without reading through or tracing the actual code (design-by-contract based on specifications rather than concrete dependency between areas of code).

Additionally, if you want longer operations to work well, you might want to adopt stricter code conventions to support them.  Tossing a return statement in the middle of an operation might be fine for a short operation, but in longer operations this can create a large section of code which is conditional but not obviously conditional on a quick read-through (just for one example).

So I would think that which style is less likely to be a bug-filled nightmare would depend in large part on what conventions you adhere to for the rest of your code.  :)

Title: What is the ideal length of a method for you?

Body:
In object-oriented programming, there is of course no exact rule on the maximum length of a method , but I still found these two quotes somewhat contradicting each other, so I would like to hear what you think.

In Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin says:

The first rule of functions is that they should be small. The second
  rule of functions is that they should be smaller than that. Functions
  should not be 100 lines long. Functions should hardly ever be 20 lines
  long.

and he gives an example from Java code he sees from Kent Beck:

Every function in his program was just two, or three, or four lines
  long. Each was transparently obvious. Each told a story. And each led
  you to the next in a compelling order. That’s how short your functions
  should be!

This sounds great, but on the other hand, in Code Complete, Steve McConnell says something very different:

The routine should be allowed to grow organically up to 100-200 lines,
  decades of evidence say that routines of such length no more error
  prone then shorter routines.

And he gives a reference to a study that says routines 65 lines or long are cheaper to develop.

So while there are diverging opinions about the matter, is there a functional best-practice for you?


问:
Domain-specific Interfaces
Are there any real benefits of using interfaces over abstract classes in a domain model? Does anyone have any experience using interfaces in a domain model in a real project?

From a technical perspective, DDD defines stereotypes like aggregate, value, repository, etc. Repositories then, for example, can be defined as interfaces like ICustomerRepository which are then implemented by the infrastructure. Now that's a valid use case for an interface, since there can be multiple implementations of the repository (mocks, fakes etc.). However that is an entirely technical reason for using it: here the interface is only used to separate domain-specific repository from its technical implementation.

But what about purely domain-specific interfaces? Has anyone ever encountered a situation in which both the interface and its realization were non-technical? In particular, what reasons could speak for choosing an interface over an abstract class when implementing a domain-specific type? Maybe when multiple inheritance is involved it would be required, but how probable is it and could it be considered a good design then?

答:
Does anyone have any experience using interfaces in a domain model in a real project?

We have lots of interfaces and there's a big problem with several of them; and that is temporal coupling - and unknowable coupling at that....

Should have been a templated abstract class

The interface method sequencing and code structure in the actual implementation makes it clear that without knowing how the methods are supposed to interact that it is impossible to implement the interface at all. Not only what methods call what other methods, but under what conditions, and with particular necessary details w/in individual methods.

After seeing the 3rd implementation it is clear that there is a refactoring screaming to get out but cannot due to what happens to code given:

the ravages of time

different coders

and worst of all different coders at different times, especially given inevitable staff turn over.

Subsequent implementations are "different without being distinctive"

The first implementation was mimicked - I am not saying cut and pasted necessarily - by the next, and next, etc. implementation with the inevitable consequence of slight differences that at close (and time consuming) inspection prove to be merely differences.

Maintenance is dis-enhanced in several ways

The absence of an abstract class structure encourages gross violations of single responsibility principle.

This thing becomes the poster child for DRY.

True functional commonality is hidden by the irrelevant implementation differences and the SRP violations.

Inevitability some implementation reveals a common bug but is fixed only where the bug is reported. This is not surprising to anyone working large projects.

Inevitability some implementations introduce bugs that would have been prevented by an abstract class with foundational implementation and error handling.

Refactoring becomes (a) too time consuming (b) too risky (c) generally impractical

Title: Domain-specific Interfaces


问:
Can one always design for scale out?
When designing an application where scalability is going to be important, it would be useful if the application could be designed to "scale out" on cheap commodity servers. However, there are many scale up applications (see my previous question).

Is it always possible to design an application to scale out, or do some requirements make scale out impossible, even if all software can be designed from scratch and no legacy software is involved?

I am looking for cases where scale out is an inferior solution to scale up, and where good application design could not mitigate this. In other words, the application cannot be designed to scale out effectively, no matter how hard one tries.

I am not looking for cases where legacy software or data structures -- or even entire architectures (as in the answer to the previous question) -- were not designed to scale out and could not be changed.

Alternatively, if there is reason to believe that one can always scale out, if the application is well designed, I would love to know that as well.

Edit: I am looking for an explicit example of such a system, if there is one.

答:
Here's an example of a design that doesn't scale. The reason is as explained by the other answers, it has to be done sequentially:

An exchange orderbook for a particular product such as a futures contract. Users are counting on getting filled on a price-time rule, so the server needs to process each entry in sequence.

OwnerDisplayName: Demetri

Title: Can one always design for scale out?


问:
If your workmate is quitting his job, would you notify your boss?
If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>

答:
No, it's not your call to make.

If he's acting unprofessionally or slacking you should tell your boss that though not the reason why, that's for your boss to speak to him about.

But you should assume all knowledge you have of his possible plans (because until he quits that's all they are and there are plenty of instances where people have a change of heart) is in confidence and shouldn't be shared.


问:
Sequentially/parallel algorithm for extracting blob outer perimeter/contour length
I have labelled the connected components in a binary image and found their areas and bounding boxes. The components are not necessarily filled, and may contain holes. I wish to identify the component that resembles a pupil the most. For this, I would also like to extract (only) their outer perimeter lengths, for calculating circularity, since these are good features for pupil detection.

I plan to do this sequentially and then move the algorithm to CUDA afterwards, so the algorithm should be parallelisable to some extent. I should note that this work is for my thesis, and I am not asking you to solve anything for me, just provide some feedback on my research so far.

I investigated tons of articles for this problem, but it seems most of them are concerned with connected component labelling and not feature extraction. Alas, I found three candidates, and <s>two</s> one of my own design:

The Marching Squares algorithm. It sounds promising (also embarassingly parallel), but it appears to extract all perimeter lengths, including inner contours, without modification, which will likely overestimate perimeter lengths. However, since I am looking for the pupil, a homogenously colored area, it will likely not overestimate the pupil. The overestimation might also yield bad results for other irregularly shaped blobs, which should be fine if they are then not selected.

The Chain Code algorithm (used by OpenCV's findContours function): Seems pertty good as well, and parallel solutions do exist, but I worry it might fail if the stopping criterion is not good enough (see here, at the bottom near Jacob's stopping criterion). However, it should be able to extract only the outer contour and give good approximations.

The Convex Hull algorithms: While parallel solutions exist, I worry that it might make a blob more circular than it really is, if points are scattered in a way that favors this. Should give good results for the pupil blob though.

<s>Algorithm 1: You could launch some threads that trace from each side of the blob's bounding box towards the opposite side. When the threads "hit" a pixel with the blob's label, they mark it as visited and sum the hits. When another side is traced, visited pixel are ignored, hit pixels are summed again etc., and the total is returned.</s>

Algorithm 2: I also tried counting the number of pixels with a background pixel in their Moore neighborhood, but this overestimates the contour if enough holes are present.

I would appreciate some suggestions before I try to code everything since I am on a schedule. Again, I'm just asking for
advice, not solutions.

答: For finding circular boundaries, I have found the Hough Transform to be very useful, especially if you know the approximate range of radii you may have in your image. </p>

OwnerDisplayName: NordCoder


答:
In my experience, most organizations use a mix of the processes that work best for it and its customers (business). While Agility is an organizational goal, that does not mean ALL its software projects need to be run using an Agile method (Scrum or others).  Agility means being able to respond to change quickly and still deliver quality products and services that meet the customers' requirements and thus organizational goals. That can be achieved with a variety of methods and approaches by the organization.

I would rather ask the question - what is the problem that you are trying to solve? Is there a problem? Does the solution require changing or examining your software development processes? Is the solution to that problem to get everyone on the same methodology?

Even so, I can assure you that most organizations today have 'agility' as a business goal in some fashion or the other - AND work with a variety of software development methods depending on the needs of the customer, the nature of the project and the skills and maturity of the team involved.

Hope that helps!


答:
There's a very serious problem with choosing a methodology on a "per-project" basis, which is that most Agile methodologies reject the notion of projects.

A project implies fixed scope and fixed time, and for many of the more dysfunctional organizations, also a fixed budget. This is anathema to every methodology out there.

Every role, every tool and every ritual in a process like Scrum centers around the product - not a "project". You have a product backlog which states what must be done and in what order (but not when or how). You have a product owner who chooses what goes on the backlog. You have product demos or showcases to inform the business of progress. You have product releases and iterations. Even your very first release is called the "Minimum Viable Product", and it's not intended to be the final release.

The closest analogy to a traditional "project" would probably be a single sprint/iteration/cycle, because at the end of a sprint, your team should have come up with one or several meaningful improvements to the product that deliver some measurable business value. If your team isn't doing this, your team isn't Agile in the capital-A sense of the word. If your team isn't dedicated to a single product (or maybe a small suite) then it isn't Agile. If people outside your team dictate requirements or deadlines to your team, then your business isn't Agile.

I am not saying that you have to be Agile. What I am saying, however, is that you can't really pick and choose. Most of the "good" Agile methodologies like Scrum include process improvement as part of the process itself (i.e. retrospectives and post-mortems), thus I am also not saying that your process should be static. To the contrary, unless everything went absolutely perfectly during your last few sprints, you should probably be tweaking the process. But Agile processes are processes for continuous delivery, and if you switch to "project" mode at any point, then you're throwing away the continuous part and you might as well just stick to a more traditional project-management process. Not waterfall, which was broken even according to Royce, but something more formal like the RUP.

In general I would say it's OK to have some Agile teams and some non-Agile teams/projects if they are different teams. I've seen what happens when businesses try to shoehorn waterfall projects into an Agile team/process, and rest assured it's not pretty; at best it seriously hurts the quality and timeline of both goals, at worst it will drive the team members so crazy that half of them quit. Avoid, if possible.


问:
Why was the first compiler written before the first interpreter?
The first compiler was written by Grace Hopper in 1952 while the Lisp interpreter was written in 1958 by John McCarthy's student Steve Russell. Writing a compiler seems like a much harder problem than an interpreter. If that is so, why was the first compiler written six-years before the first interpreter?</p>

答:
The other part of the equation is that compilers were a step abstraction above an assembler. First we had hard-coded machine code. "We" were the assembler. Every jump and offset, etc. was hand-calculated into hex (or octal) and then punched into paper tape or cards. So when assemblers came on the scene, it was a huge time-saver. The next step was macro assemblers. That gave the capability to write a macro that would expand into a set of machine instructions. So Fortran and Cobol were a huge step forward. The lack of resources (storage, memory, and cpu cycles) meant that general purpose interpreters had to wait for technology to grow. Most early interpreters were byte-code engines (like Java or CLR of today, but with much less capability). UCSD Pascal was a very popular (and fast) language. MS Basic was a byte-code engine under the hood. So the "compile" was really to generate a byte-code stream that was actually executed by the runtime.

In terms of instruction overhead, it totally depended on what processor was being run. The industry went through a big RISC vs CISC turmoil for a while. I personally wrote assembler for IBM, Data General, Motorola, Intel (when they showed up), TI, and several others. There was a fairly significant difference in instruction sets, registers, etc. that would influence what was required to "interpret" a p-code.

As a time reference, I started programming in the phone company around 1972.


答:
It depends.  How well defined are your requirements? How much of the system is UI facing?

From my experience most customers do not know what they want until they see something in front of them. So I normally provide some wire-frames of key UI aspects or deliver the majority of the UI (non working). This allows for the customer to change their mind on features/functions without too much impact as the database design and code structure is still only in design phase - it is easy to amend the design.
It is orders of magnitudes easier/quicker to change design earlier in the project then later.

Agile states you should also work on the most difficult items and the most important items first. Fail fast. So once the customer has seen the UI I focus on building small components which are fully functional talking the most important and hardest to implement first so you know as soon as possible if your going to run into any hurdles.

Then you have your sprints and have constant communication with the customer developing both the UI and functional aspects at the sometime.

Body:
Generally speaking, is it better to make all the functional parts or get UI working first - or a mix of the two?

Assuming you're working on something large, is it generally accepted practice to get all the functional data harvesting blobs working before any UI, get all the UI working one piece at a time as you go, or something in the middle?

We all know to break work down in to manageable pieces, but the question is ultimately whether UI is included in manageable pieces I suppose.

For the case of the example, consider a GUI application with one root window, but over a dozen tabs in various docks to separate different data components.  Each individual tab has a relatively complex set of moving parts behind it from a functional units perspective.

The example application in this particular question is here with the accompanying blog and the original commercial product.


答:
I think TomTom's answer came close to how I feel about it.

More and more I find myself going on cyclomatic complexity rather than lines.

I normally aim for no more than one control structure per method, with the exception of however many loops it takes to handle a multi-dimensional array.

I sometimes find myself putting one-line ifs in switch cases because for some reason these tend to be cases where splitting it out hinders rather than helps.

Note that I do not count guard logic against this limit.


答: Another factor:  When the first compilers were written the cost of machine time was a lot higher than it is now.  Interpreters use a lot more machine time.</p>


问:
Testing an MMO server
I'm working on a server for a very large (feature wise) MMO. After some bad experiences with breaking changes that caused bugs weeks down the line, we'd like to add unit/automated/regression tests to our project before we get much father (we've implemented approximately 5% of our requirements).

We haven't really used "serious" tests before (we've done the tutorial check-division-by-zero testing) so I thought I'd locate some guides for developing client-server test solutions. I was not able to find anything of much relevance. How should I deal with testing the following aspects of a typical server?

Testing the client-server communication (API can be broken down into "parsing", "handling" and "sending" stages)

Testing changes to an SQL database

Testing security measures

Testing around security measures (ie, making sure our tests don't trip our own security code)

Testing timed events

In case it's relevant, our language is C#, .Net 4.5

答:
Automated testing should be all about testing smallest pieces of functionality in as big isolation as possible. This allows you to define tests clearly, define most of the edge cases and have tests run in short time. Trying to test through multiple layers of code results in unclear tests, hard to test edge cases and tests that might take days to run.

So I would recommend to immediately drop the idea of testing the whole "server" as one big bulk of functionality from request handling to game logic. Instead, try to pinpoint the most error-prone code and test just that in as much isolation as possible. This would probably require refactoring, because code that is written without automated tests in mind is rarely testable. That way, you don't have to worry about most of the things on your list.

Title: Testing an MMO server


问:
How should data transfer between a client and a web API for normalized data be designed?
I want to design an API backed by some database (doesn't really matter which, but to make the discussion more interesting, let's say it's Mongo - explanation below) which sends data to a client.

The database contains several types of records. Some of them reference other types of records.

It's not uncommon for a record to be referenced by several other records from different types. Thus the data on the DB is normalized.

What are the considerations in designing an API server which sends records to the client?

Two options come to mind (you're invited to suggest more or correct me on those):

The API is granular. Send normalized data. Let the client ask for
more records based on what it receives. The client may have a cache, it
may decide it doesn't need to ask the server for everything.

The API sends all the records the client might possibly need based on the
requested data. Thus effectively denormalizing the data.

With option 1, the client may make more HTTP requests so it can have the complete data it needs. It means more network communication, which may make the total data transfer slower. The server is simpler though, and the client can selectively ask only for the records it doesn't already have.

With option 2, less HTTP requests. But we may send the client data it already has (maybe it already received, and cached, some of the records in a previous request). The server is more complicated. Especially if it's not RDBMS. No joins in Mongo, so we have to query the DB more than once to get all the data.

Further assumptions:

The data changes every few days (2-3 times a week). So the client can potentially have a persistent cache.

The Mongo queries are a bit slow (millions of documents in each collection).

In each such session about 2MB of data will be sent to the client.

答:
Option 1

While it is tempting to have a set of lightweight APIs that send the normalized data, there are some potential pitfalls with this approach.

First, the lightness of these APIs might end up being paid for with tight coupling between your normalized data model and your APIs. If you want to change your data model or APIs, you will have to change the other or engineer a means of preserving the old approach on the other side of the change. This complicates maintenance.

Second, you are correct to note that there will be lots of HTTP calls from the client to your APIs. Put yourself in the role of the implementor of the client and ask whether you really want to make all those API calls. With proper error checking and exception handling, it gets to be a lot of work.

Option 2

On the other hand, sometimes a "one call does it all" approach is the best one. The "send everything" approach of option 2 can be a lot easier for the client, and due to its denormalized nature, provides a de facto interface between client and server that should be straightforward to maintain as the two develop and evolve separately. The price with this is speed and size. As you note, it could take a while to assemble all that data, then transmit it, especially if only a small portion of it is needed. But don't forget, it will be a lot faster to fetch all the data over the LAN in your data center than for the client to do so over the open internet.

Recommendation

I lean toward option 2, though I propose adding a dose of option 1 to strike a balance between simplicity and performance. If some data takes exceptionally longer than average to assemble, then see if you can leave it out of the main API and put it in a separate one. Remember, the goal is to make it easy on both the server and the client.

Caching Caveats

Since the data is changing every 2-3 days, be careful about caching. Since the data is so big and expensive to assemble, caching it tempting and probably a good idea. However, since it is changing regularly, be sure to refresh the cache and take steps to force the client to fetch new data when it is available. Techniques like cache-busting API parameters, observation times, expiration times, and the like could be of service here.


问:
Creating system diagrams for a small app
I am learning system design (on my own) and still I am not clear on a few things. Assume there is a simple application with a front-end and a database for storing of the data.
In the system architecture diagram, will there be only two parts (UI and DB) or should I include some UI modules for calculations, for example? And what about hardware devices that the system is using?

To give a more precise example: I have an application that is used by two types of users (one has limited access). This app uses a DB and its modules are working with an external hardware device.

I am not sure how should I start with the system diagram.

答:
You can make your system diagram as simple or as complex as you like. The goal is to express your design with the maximum clarity and efficiency. If two boxes are sufficient, use that. If you need more, then use more.

As you add components to your diagram, ask yourself whether they contribute substantively to the whole. For example, even through your system will likely use a disk drive, you probably don't need to add it to the diagram since it is so common and fundamental and not especially specific to your project. But if the hardware is unusual or a big focus of the system, then including it would probably help with the clarity of the diagram.

Alternatively, the presentation of information in a UI and its storage in a database are often very different. I suspect you might end up with a middle layer that translates between the two. Such a middle layer probably deserves to be called out in your diagram.

As a final note, things get different if your diagram is going to be part of a patent application. The PTO likes hardware-oriented designs, so including HW components might be advised. Talk to someone well versed in patent applications to be sure.


问:
Writing a new programming language - when and how to bootstrap datastructures?
I'm in the process of writing my own programming language which, thus far, has been going great in terms of what I set out to accomplish. However, now, I'd like to bootstrap some pre-existing data structures and/or objects.  My problem is that I'm not really sure on how to begin.

When the compiler begins do I splice in these add-ins so their part of the scope of the application?

If I make these in some core library, my concern is how I distribute the library in addition to the compiler--or are they part of the compiler?

I get that there are probably a number of plausible ways to approach this, but I'm having trouble with the setting my direction.  If it helps, the language is on top of the .NET core (i.e it compiles to CLR code).

Any help or suggestions are very much appreciated!

答:
Since you are building a language on top of the .NET runtime I think what you want to do is distribute a DLL that will initialize the wanted structures/environment, then call an entry point in that DLL in your compiler-generated MSIL code, before you execute the main() function (or however your programming language finds its entry point) of the user's program.

This is analogous to how libc variables and runtime dependencies are initialized by assembly code that is executed before the user's main() function [or more precisely the assembly code generated for the prolog+body of main()] is actually called in C.


答: I would NOT. If your Manager is smart he probably knew it before you did and has already taken proactive measures to take care of it. If he doesn't know it even then it is not your business to interfere in your workmate's life. What if you tell the Manager and the guy chooses to stay back ?</p>

Title: If your workmate is quitting his job, would you notify your boss?

Body: If a colleague on your team is planning to quit his job and this may cause bad feelings in your company, would you notify your boss?</p>