答:
The problem with Object Oriented Programming is exactly that, the shape and vehicle examples. What I'm going to type below is not the actual truth, it is an opinion. An opinion shared by more people than just me though :)

Object oriented vs "Class oriented"

Your example where there would be a catalog and an episode is perfectly well. The problem is the functions you propose these Objects should get. That is where you go from Object Oriented Programming to Class Oriented Programming. Just fitting a lot of methods concerning the same concept in an Object doesn't make programming object oriented. All you do is make some sort of container for methods.

The Episode Object should be just an Object that "models" the Episode. It has a title, content, author, that kind of stuff. In no way should this Episode have access to the database. It is not supposed to save itself or be able to load more instances of other episodes. The same goes for Catalog, it should not be able to retrieve its newest Episode itself. A catalog is a model, it has a title and some other stuff.

Splitting up responsibilities

Getting stuff from and saving stuff to a DataBase is not a models responsibility. So someone else has to do the job. A good start might be to create a CatalogRepository which could look like so:

```<code>CatalogRepository
{
    /**
     * @param int $id
     * @return Catalog
     */
    public function getCatalogById($id)
    {
        //Do a query, populate a new Catalog and return it.
        //The constructor of Catalog should not be the one quering!
        //It should receive data, nothing more
    }

    /**
     * @param Catalog $Catalog
     */
    public function saveCatalog(Catalog $Catalog)
    {
        //stuff....
    }

    /**
     * @param string $name
     * @return Catalog[]
     */
    public function searchCatalogsByName($name)
    {
        //do a full text search or something?
    }
}
</code>```

The Episode would have something along the same lines where you could get all Episodes for a specific Catalog but also the five most popular Episodes:

```<code>class EpisodeRepository
{
    /**
     * @param Catalog $Catalog
     * @return Episode[]
     */
    public function getEpisodesByCatalog(Catalog $Catalog)
    {

    }

    /**
     * @param int $amount
     * @return Episode[]
     */
    public function getMostPopularEpisodes($amount)
    {

    }
}
</code>```

There are some really good guidelines for writing good object oriented code, take a look at SOLID for instance

Title: Simple real-world PHP OOP example?

Body:
I'm trying to learn PHP OOP, but when I've followed tutorials, all the examples seem to involve things like:

```<code>class Human {
    $_sex;

    public function setSex($sex) {
        $this->_sex = $sex;
    }

    public function getSex() {
        return $this->sex;
    }
}
</code>```

(Pointless example, but hopefully you get what I mean -- An object has properties that are stored in the object.)

I've never come across a web application where I've needed to create objects about humans, dogs, cars, or any of the other weird examples you find when reading tutorials about OOP...

So I'm trying to find a similarly simple, but more realistic, project with which to learn OOP. I've chosen a website for an internet comic (e.g. XKCD.com). (This would allow people to view the comic, but also the author to edit and update it.)

So how would this translate to real-world PHP OOP?

My initial instinct would be to break the objects down thusly:

Catalogue

Episode

Where the Catalogue class would contain methods pertaining to all the episodes of the comic, e.g. getMostRecentEpisodeID(), deleteEpisode($episodeID), addNewEpisode($newEpisode), etc. etc.

And Episode would contain methods pertaining to the individual episode, e.g. getEpisodeComments($episodeID) (if the website allowed people to leave comments on individual episodes), editEpisode($episodeID), getEpisode($episodeID), etc.

Is this right, or have I made an absolute hash of what OOP is for?

Edit: Rather than just giving me a list of examples, it would really be helpful if your answer made specific reference to the problem I'm trying to solve.

Thanks.

Body:
The problem with Object Oriented Programming is exactly that, the shape and vehicle examples. What I'm going to type below is not the actual truth, it is an opinion. An opinion shared by more people than just me though :)

Object oriented vs "Class oriented"

Your example where there would be a catalog and an episode is perfectly well. The problem is the functions you propose these Objects should get. That is where you go from Object Oriented Programming to Class Oriented Programming. Just fitting a lot of methods concerning the same concept in an Object doesn't make programming object oriented. All you do is make some sort of container for methods.

The Episode Object should be just an Object that "models" the Episode. It has a title, content, author, that kind of stuff. In no way should this Episode have access to the database. It is not supposed to save itself or be able to load more instances of other episodes. The same goes for Catalog, it should not be able to retrieve its newest Episode itself. A catalog is a model, it has a title and some other stuff.

Splitting up responsibilities

Getting stuff from and saving stuff to a DataBase is not a models responsibility. So someone else has to do the job. A good start might be to create a CatalogRepository which could look like so:

CatalogRepository
{
    /**
     * @param int $id
     * @return Catalog
     */
    public function getCatalogById($id)
    {
        //Do a query, populate a new Catalog and return it.
        //The constructor of Catalog should not be the one quering!
        //It should receive data, nothing more
    }

    /**
     * @param Catalog $Catalog
     */
    public function saveCatalog(Catalog $Catalog)
    {
        //stuff....
    }

    /**
     * @param string $name
     * @return Catalog[]
     */
    public function searchCatalogsByName($name)
    {
        //do a full text search or something?
    }
}

The Episode would have something along the same lines where you could get all Episodes for a specific Catalog but also the five most popular Episodes:

class EpisodeRepository
{
    /**
     * @param Catalog $Catalog
     * @return Episode[]
     */
    public function getEpisodesByCatalog(Catalog $Catalog)
    {

    }

    /**
     * @param int $amount
     * @return Episode[]
     */
    public function getMostPopularEpisodes($amount)
    {

    }
}

There are some really good guidelines for writing good object oriented code, take a look at SOLID for instance


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
In non-software companies (banks, insurance) with in-house IT the money comes from various business groups. The business groups directly gets sales pitch from vendors and will push it on to the IT. They are paying for the software/hardware and your salary so your protests will go no where.

Paying for bloated applications and middleware that costs mid-high five figures and doesn't even fit within the existing system architecture

Using expensive software like HP QualityCenter, BMC Remedy, HP LoadRunner etc where better and cheaper options are available

With multi city teams a lot of travel costs, sometimes for only a few hours of meeting

Paying for windows 7 license that somes with new machines and then paying again to downgrade to windows XP as the new SOE (designed in 2010) is still XP

Over capacity in hardware

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: kanad


问:
Unindented elses
Been writing code since about 18 years now. Lately, I've got into the habit of not indenting elses and when I look at the code it does worry me a bit mostly that someone who might look at the code might cry foul.

The snippet below explains the need for the style

```<code>if(condition) {
   ...
} //1
if(condition) { // Don't want this second block to be entered unnecessarily
   ...
}
</code>```

So I put an else where the comment labelled 1 is

```<code>if(condition) {
   ...
} else
if(condition) {
   ...
}
</code>```

Putting an else there helps maintain readability especially when forgetting to put one there doesn't necessarily break anything. What I'm uneasy with is that it doesn't strictly follow conventions (Sun's in this case) in two different ways - 1) proper indentation 2) having an open brace after the else

I guess what I'm trying to do is prevent having massive indents which really makes a difference in blocks that have a lot of conditions - 5 or more although only three are showcased below.

```<code>if(condition) {
   ...
} else {
   if(condition) {
      ...
   } else {
      if(condition) {
         ...
      } else {
         ...
      }
   }
}
</code>```

I find it a lot neater to have the else unindented and without a brace following. What are your thoughts?

答:
I usually see this solved by not putting the if inside a code block if it's the only statement in the else-part and  putting the if one the same line.

This effectively emulates the elseif or elif of other languages.

```<code>if (condition1) {
  ...
} else if (condition2) {
  ...
} else {
  ...
}
</code>```

This way there's no useless indentation and every code block has its braces, as it should be.

I also never had any code quality tool nag at me for this, so I assume it's widely accepted.

ContentLicense: CC BY-SA 3.0

Title: Unindented elses

Body:
I usually see this solved by not putting the if inside a code block if it's the only statement in the else-part and  putting the if one the same line.

This effectively emulates the elseif or elif of other languages.

if (condition1) {
  ...
} else if (condition2) {
  ...
} else {
  ...
}

This way there's no useless indentation and every code block has its braces, as it should be.

I also never had any code quality tool nag at me for this, so I assume it's widely accepted.


问:
How to deal with a Team Lead who dislikes Extreme Programming?
From http://en.wikipedia.org/wiki/Extreme_programming

Extreme Programming is a software development methodology which is intended to improve software quality and responsiveness to changing customer requirements.

My Team Lead dislikes Extreme Programming as

May take more time to complete the project.

Increases initial cost (20% or more).

Constant interaction is tiresome.

Unit tests is hard for database, distributed and GUI.

Is there any evidence to support these claims about Extreme Programming or are these fabrications?  What arguments can be made where Extreme Programming can actually be harmful to a team or project?

答:
With methodologies like XP and Agile, you are always going to get zealots on both sides, for and against.

With some people who are against, you may never change their mind.

So I would first of all think carefully about this, and evaluate realistically whether you think this person could ever be convinced.

Some battles are not worth fighting. Especially if you are for want of a better phrase "just a developer" - changing the whole software development process may be well outside your remit.

Instead, maybe go for the easy things that could help your dev team, pick and choose parts of XP you like and try and introduce them, instead of big bang trying to change the whole methodology.

If you still go ahead with trying to convince him, make sure you have well documented facts that answer/refute each of his concerns. Show that some of his concerns actually happen using your current methodology.


问:
How to document events?
Code documentation is usually related to a piece of code, be it small (method-level) or larger (class- or namespace-level). However, it is always about the inputs and the outputs of that piece of code, possibly describing its behavior and caveats.

It doesn't make much sense to document events fired by a class in the methods that may fire them: they may be duplicated and, by the definition of events, the listener is not expected to care about what triggers them, only handling them.

Documenting all events at the top of a class seems quite heavy, as someone willing to get an overview of the class behavior might not be so interested at deep diving at this “secondary interface”.

This problem is mitigated in strongly-typed languages such as Java (yes, unless you use anonymous classes, but it doesn't seem so common), as the events will be defined in their own classes, which can then be documented.

But, in languages with looser types, where an event is simply a String identifier and a series of parameters, it is much more difficult to find the proper place for documenting these id/params combinations.

So: where should fired events be documented in languages that don't model them explicitly?

答: Every method should document it's gazintas and gazoutas.  The things that go into a method include its parameters, and relevant states of the object it belongs to.  The things that go out of it include its return value, relevant changes in the object's state, events it fires, changes to persistent data, etc.  One key point of code documentation is to answer the "Who am I?  Why am I here?" questions.  If you have to read the code to learn those answers, the documentation is insufficient.

Title: How to document events?


答:
Technically, there are 3 cases here.  It may increase the time.  It may not, and it may have no effect.  Not trying to be flippant, but this is an unprovable condition.  There are cases where switching to an Agile method saved the project.  Likewise, there are cases where that switch killed the project.  There are too many variables involved to make generalities at the level we're discussing.  An assessment has to be made by those who know their current process best and evaluate whether XP (or any other methodology) is a good fit.

This is true if you're not currently using XP.  But this is true for any new methodology.  There are start up costs associated with changing your development methodology.  Employees need to be trained; management needs to be convinced; tooling needs to be modified; etc...  XP is not a magical solution that waives away those transition costs.

For introverts, this is very true.  Pair Programming via XP is not for everyone.

Unit tests are hard, period.  It takes a commitment by the organization to create and maintain them.  XP isn't a magical solution in this case either.

It doesn't really matter what the evidence is - your team lead has made up his mind.  Forcing a confrontation and waiving published studies around will merely frustrate both you and him.

If you're committed to the benefits of XP, then you need to start adopting the methods that you can within your own work.  When you start delivering higher quality work items faster than your peers, then your team lead may listen.

It's also worth noting that XP may be contraindicated for some industries.  Defense sector work, for example, is very document / artifact heavy due to the contracts and multiple parties involved.  XP and other Agile methods tend to be lighter on the documentation and therefore aren't appropriate.  Likewise, projects that are being outsourced don't fit well with the Agile model as the requisite interaction for requirements gathering and verification simply aren't as easily accomplished.

I'm not trying to bash XP, it has it's value.  But it's a tool and you have to know when it's appropriate to use that tool or not.

Title: How to deal with a Team Lead who dislikes Extreme Programming?

Body:
From http://en.wikipedia.org/wiki/Extreme_programming

Extreme Programming is a software development methodology which is intended to improve software quality and responsiveness to changing customer requirements.

My Team Lead dislikes Extreme Programming as

May take more time to complete the project.

Increases initial cost (20% or more).

Constant interaction is tiresome.

Unit tests is hard for database, distributed and GUI.

Is there any evidence to support these claims about Extreme Programming or are these fabrications?  What arguments can be made where Extreme Programming can actually be harmful to a team or project?


问:
Why isn't the ‘format’ method more widely used in Python?
I'm probably missing something here, after searching I couldn't find an answer.

I've explored quite a few Python projects and one thing I keep noticing is the fact that the majority of them continue to use the % operator for formatting strings rather than the newer, recommended .format() method. Is there a reason for this? it seems like a trivial change, unless I'm missing something entirely.

For example:

```<code># count how many times the % operator technique is used
find . -name "*.py" -exec grep -HE "\"[^\"]+\"\s\%\s\w+|'[^']+'\s\%\s\w+" {} \; | wc -l

# and the same for format()
find . -name "*.py" -exec grep -HE "\w+\.format\(" {} \; | wc -l

# Results:
#
#               % operator        format()
# iPython          670               63
# Django           977               8
# Tornado          91                0
# requests         25                1
</code>```

No real reason for this question, just curious.

Cheers guys!

答:
Three extremely strong inclinations come together to produce this effect:

Comfort: "I know how to do this the old way, learning the new way would be more effort."

effort/effect trade-off: "Is the old method gone? Is it even deprecated? No? Then there is no business case whatsoever for changing this. Create new code instead."

Safety: "Are you sure the proposed new way of doing things is exactly equivalent? No? Then better leave the old code as it is - you might introduce defects."

All three are, in fact, quite sensible (the first one least so, since continual learning is what information workers should thrive on).

(Edit: As pointed out below there is a fourth point: not knowing that the new method even exists! This is less sensible, but might actually be the most common one.)


答: In addition to the other reasons, I would add backward compatibility and consistency. Often you need to write scripts that can run on other people's computers, who are be unwilling or unable to upgrade to the latest and greatest Python. So you write to the lowest common denominator. By the time enough of your users have upgraded to a sufficiently recent version of Python you have probably forgotten which features appeared in which version of Python. Unless they are exceptionally valuable features, it may well not be worth the time to research, consider and decide whether it's now safe to use each feature. The format method method is a nice API to use in new code, but the case for introducing it to a code-base that already uses % extensively is not so strong.</p>

Title: Why isn't the ‘format’ method more widely used in Python?

Body:
I'm probably missing something here, after searching I couldn't find an answer.

I've explored quite a few Python projects and one thing I keep noticing is the fact that the majority of them continue to use the % operator for formatting strings rather than the newer, recommended .format() method. Is there a reason for this? it seems like a trivial change, unless I'm missing something entirely.

For example:

```<code># count how many times the % operator technique is used
find . -name "*.py" -exec grep -HE "\"[^\"]+\"\s\%\s\w+|'[^']+'\s\%\s\w+" {} \; | wc -l

# and the same for format()
find . -name "*.py" -exec grep -HE "\w+\.format\(" {} \; | wc -l

# Results:
#
#               % operator        format()
# iPython          670               63
# Django           977               8
# Tornado          91                0
# requests         25                1
</code>```

No real reason for this question, just curious.

Cheers guys!


答:
Addition to @KilianFoth's answer; porting a big project to an upper software version have too much work to do. And changing an un-deprecated usage have the least importance in the upgrade process.

Probably they are using new format in totally re-written parts and do not change the existing usage on the rest.


问:
Combine auto-syncing cloud and VCS
This question brought me to another question: is there any VCS/tool for a VCS which automatically backups your source code between the last checkout and current changes?

I had the problem of loosing uncommited source code changes just one week ago.

I did not want to commit yet because the changes were incomplete. But then, an error when moving the data to an USB stick caused the data loss.

That's the opposite what a cloud service (like Google Drive, SkyDrive, DropBox, ...) does: it tracks each change you made!

Have you lost your data? That's no problem because you have the latest version online.

So what would a combined solution look like?

It would offer full functionality of a VCS including auto-syncing of any intermediate changes between two commits/checkouts to a temporary online location.

答:
I don't know what VCS you are using, but if it's a DCVS like git or Mercurial, you can simply commit along the way, even un finished/unstable edits, then rewrite history (through git rebase or the mercurial equivalent), before pushing.

That's one of the main interest of DCVS

Title: Combine auto-syncing cloud and VCS


答:
I don't know of any evidence proving adverse affects of extreme programming that would be usefully conclusive for XP teams in general.  And proving them right might not be the most effective approach to influence change.

It's something that only experience and experimentation can demonstrate XP's effectiveness for the team as a whole.

The team lead sounds like they are understandably worried about XP's affect on 'velocity'.     Take a look at Scrum (also the Scrum Guide is a very good introduction).  Scrum focusses on the process of developing the product by breaking it into manageable chunks of product increment (called Sprints).  This could be used to take XP/Agile practises (unit testing, pair programming) and prove to team leads/management that you can still maintain velocity whilst achieving increments in product.  It would provide evidence over time that your team will spend less time fixing regression style bugs and more time on customer features.


问:
Template method within one class without subclasses or inheritance
I have an algorithm with mostly invariant parts that needs to be reused within one class so as to stay DRY.

Code duplication with repeating method structure

```<code>public void save(String key, int value) {
    try {
        if (isValidWrite()) {
            // Only variable part
            editor.putInt(key, value);
            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}

public void save(String key, String value) {
    try {
        if (isValidWrite()) {
            // Only variable part
            editor.putString(key, value);
            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}
</code>```

Solution?

The template method pattern is not applicable, because it requires sub-classing.

Strategy - do I really need to create an interface and provide different implementations to pass into a generalized method as a delegate? Maybe I'm just complaining about proper support for delegates in Java.. (in C# could just use a generic Action<>)

答:
```<code>protected void applyParameters(Editor editor, Object [] parameters) {
    for(Object param : parameters) {
        if(param instanceof Integer) {
            editor.putInt(key, param);
        } else if (param instanceof String) {
            editor.putString(key, param);
        } else {
            // case for unknown type?
        }
    }
}
public void save(String key, Object ... params) {
    try {
        if (isValidWrite()) {
            if(params != null)
                applyParameters(editor, params);

            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}
</code>```

Try this.  Essentially, you cannot generalize "putInt" and "putString", but you can at least extrapolate them into their own method.  Just provide a case for parameters you do not recognize as valid.

Body:
protected void applyParameters(Editor editor, Object [] parameters) {
    for(Object param : parameters) {
        if(param instanceof Integer) {
            editor.putInt(key, param);
        } else if (param instanceof String) {
            editor.putString(key, param);
        } else {
            // case for unknown type?
        }
    }
}
public void save(String key, Object ... params) {
    try {
        if (isValidWrite()) {
            if(params != null)
                applyParameters(editor, params);

            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}

Try this.  Essentially, you cannot generalize "putInt" and "putString", but you can at least extrapolate them into their own method.  Just provide a case for parameters you do not recognize as valid.


问:
Is it possible to get dynamically generated html in asp.net tags using HTTP Modules?
I want to know if it is possible to write to a log/text file dynamically generated HTML in asp.net tags in an .aspx page using HTTP modules.

By dynamically generated HTML, I mean the html content that asp.net generates in response to statements between the tags <% %> or <%# %> or <%$ %>.

So when asp.net renders a page, it essentially converts everything into HTML. There is some static html written in the asp.net page, rest is what i call dynamically genrated HTML. My goal is to dump somewhere all the dynamically generated HTML content.
Can it be done using HTTP Modules or any other mechanism ?

Example:

If the .aspx page is like this

...

        Total Credit Line

            <%=creditLimit.ToString("C")%>

...

I want the HTTP Module to write in a log file, the HTML rendered by the <%=creditLimit.ToString("C")%> asp tag and all other asp tags on the page. The HTTP Module would be generic and can be added to any IIS website.
Note that there would be no difference in the output that is seen by a browser.

答:
I want the HTTP Module to write in a log file, the HTML rendered by
  the <%=creditLimit.ToString("C")%> asp tag and all other asp tags on
  the page. The HTTP Module would be generic and can be added to any IIS
  website. Note that there would be no difference in the output that is
  seen by a browser.

Putting aside why you would want to do this...

I would add a method to the Object called ToStringAndLog() The method would log it then return this.ToString()

When you want an Log a Particular ToString() action use ToStringAndLog() or always use ToStringAndLog() and add a flag to the object that turns Logging on and off.

You could Override the ToString() if you wanted to add this functionality to a ton of existing code.


问:
Code reuse via inheritance
I have a set of classes that are all dealing with some related tasks. These tasks do have different inputs and outputs. This causes it to become impossible to have the tasks done via shared code without having this code be a pile of if-else statements handling all the different cases.

Now someone refactored this code to use inheritance - there now is an abstract base class that holds methods for each of which it is used by some of the deriving classes, for some of which they get overridden or nullified and some of which are always called though not always applicable for the deriving class. Furthermore the inheritance is not used for polymorphism at all, just code reuse.

I cringed a bit when I noticed this refactoring was done and that it happily got through code review. The codebase I am working with has existed for quite a while and is full of these kind of things, and most people don't understand the issues. I'm thus looking for a good overview of why inheritance should not be abused like this, esp including all the problems it causes.

答:
The keyword (or phrase) to search for here is composition over inheritance. It's a popular design guideline and you can find a general introduction at wikipedia.

Additionally, there is a community question here which provides you with a huge number of arguments on when to prefer CoI. As indicated by several (and highly valued) answers, the basic guideline for deciding between composition and inheritance is the Liskov substitution principle, which should be adhered to when using inheritance.

Title: Code reuse via inheritance


问:
Fast compression in C++ and decompression in C#

Overview

I am working on a client-server application. The client is written in C++ (working on Windows, planning to support Linux) and the server is a .NET RESTful service. I need to HTTP POST some data to the server. The data is a unicode string that I need to compress using any fast compression algorithm (needs to be light on CPU). On the server I need to decompress raw bytes and get a string.

Problem

I cannot decompress raw bytes and I end up with decompressor's output buffers stay intact.

I tried

I have tried using Google Snappy, there is only a C/C++ version and any .NET ports don't appear to be finished. I also checked LZ4, where compression/decompression works in a single language, but when I try to use both - I cannot decompress data correctly (the decompressed bytes are set to 0s).

Question

Has anyone tried using a fast C/C++ compression and C# decompression? Any recommendations?

Client application shall not use more than 5% of CPU - that's a vague requirement I have. I plan to try gzip and maybe deflate, but I am not sure if I can configure compression levels there or whether it will work in both C/C++ and C#. Client collects some near real time data into a small buffer, when that buffer gets full it shall be compressed and POSTed. The whole OS process shall take less than 5% of the machine's CPU. A buffer is roughly posted 2 times a second which creates a traffic of about 2Kb/sec.

答:
Both LZ4 and Snappy has been ported to .NET recently.

You can find LZ4 .NET port here at http://lz4net.codeplex.com.

You can find Snappy .NET port (actually P/Invoke wrapper) here at http://snappy4net.codeplex.com.

You can also check performance comparison (of .NET ports) here.

To answer your question I did use both to test C++ compression and C# decompression and it works fine.

Disclaimer: yes, both LZ4 and Snappy has been ported/wrapped by me.


问:
Storing 'sensitive' data in settings file
I'm writing a small utility in AutoIt that connects to Twitter. I would like to store the username and password in the programs setting file, but I know that it needs to be encrypted obviously. Previously when I've done this for personal use I've just adopted an iniformat - written to a temporary file and then encrypted it using a rediculously long password and 256 bit AES encryption, just calling the file "settings.eini".

However, I'm going to be offering this utility to the public. I don't expect a large amount of people to use it or for it to become a target, but I thought that it's best not to take chances. I've been reading about  creating custom file extensions and it seems like something I want to avoid for now, so is there a standard/acceptable way of doing this?

答:
Encryption is only as good as the means to decrypt it.  While it keeps out most people, anyone with reasonable knowledge of encryption could reverse engineer the username and password.  So logically, the solution is to make it difficult to reverse engineer.  The best mentality to adopt when trying to achieve this is assuming that someone wanting to crack your program knows everything that you know, how do you make it difficult to decrypt even then?

One solution that I've found is by drawing from some information that's unique to that computer like, say, the hard disk serial number.  Using that as a key, you can encrypt and decrypt the username and password and so long as your source code is protected and your program is obfuscated, nobody would be the wiser.  It only has the minor downside that it can't decrypt these values if the folder is copied to another computer (hence a different hard disk serial number).

Another approach is to make a formal https request to a server which provides a key that is used to encrypt and decrypt, making it impossible to decrypt by using the key, since the key is not saved locally.  It has the drawback that it requires the computer to be online, but since it has to access twitter anyway, I'd say that drawback doesn't apply to you.  It also doubles as a way for you to authenticate usage of your program by proving that the license used for that program isn't used under a different IP.  This is becoming an increasingly popular approach since the number of computers that work offline are always fewer and fewer.


问:
Deterministic and controllable fully automated memory management
Fully automated memory management increases productivity and integrity greatly, but usual implementation (GC) has a critical problem. It's non-deterministic, and not controllable. This causes many problems such as burst CPU load which is critical for realtime applications. Some kind of optimizations (incremental/concurrent GC) can reduce those problems but still non-deterministic and can't eliminate the problem completely.

I have been thought GC never can solve this problem, but recently, I learned and realized that GC operation doesn't need to be fully hidden. GC also can be deterministic and CPU burst-free by exposing some properly designed behavior controls.

I think (RC + manually invoked cycle detection) can do this. But this doesn't look efficient. Is there any better approach for deterministic and controllable fully automatic memory management implementation? Or can I get some link to example implementations?

Edit

I added these lines to make my question more clear.

deterministic and controllable in this context means user can track and run code at object creation and destroying explicitly. And also controls amount and time of memory management operation load.

fully automatic means it allocates and clears memory as like GC without extra concern.

答:
Let me re-phrase that.

"Is there any way I can get a memory management system which is absolutely perfect and has every desirable property?".

No such systems exist.


答:
This is al alternate solution, you expose two methods, one for ints and one for Strings.

A private method receives both kind of values and decides what to save.

```<code>public void save(String key, int value) {
    save(key, new Integer(value), null); // pass null in String param
}

public void save(String key, String value ) {
    save(key, null, value); // pass null in Integer param
}

private void save(String key, Integer intVal, String strVal){
    String strToLog="";
    try {
        if (isValidWrite()) {
            if ( intVal != null) {
                editor.putInt(key, intVal);
                strToLog = intVal.toString();
            } else if ( strVal != null) {
                editor.putInt(key, strVal);
                strToLog = strVal;
            }

            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ strToLog);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}
</code>```

Title: Template method within one class without subclasses or inheritance

Body:
I have an algorithm with mostly invariant parts that needs to be reused within one class so as to stay DRY.

Code duplication with repeating method structure

```<code>public void save(String key, int value) {
    try {
        if (isValidWrite()) {
            // Only variable part
            editor.putInt(key, value);
            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}

public void save(String key, String value) {
    try {
        if (isValidWrite()) {
            // Only variable part
            editor.putString(key, value);
            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ value);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}
</code>```

Solution?

The template method pattern is not applicable, because it requires sub-classing.

Strategy - do I really need to create an interface and provide different implementations to pass into a generalized method as a delegate? Maybe I'm just complaining about proper support for delegates in Java.. (in C# could just use a generic Action<>)

Body:
This is al alternate solution, you expose two methods, one for ints and one for Strings.

A private method receives both kind of values and decides what to save.

public void save(String key, int value) {
    save(key, new Integer(value), null); // pass null in String param
}

public void save(String key, String value ) {
    save(key, null, value); // pass null in Integer param
}

private void save(String key, Integer intVal, String strVal){
    String strToLog="";
    try {
        if (isValidWrite()) {
            if ( intVal != null) {
                editor.putInt(key, intVal);
                strToLog = intVal.toString();
            } else if ( strVal != null) {
                editor.putInt(key, strVal);
                strToLog = strVal;
            }

            if (!writeOnDisable){
                write(editor);
                Log.v(TAG, "Saved " + key + " | "+ strToLog);
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "save", e);
    }
}


问:
How important is encapsulation?
As a student in programming, I learned that encapsulation is one of the most important principles of object-oriented programming.

However, I only follow that principle when I feel like it suits my purpose. I sometimes leave internal class variables public if they are intended to be directly read at some time, and only use things like setters and getters when there are actual calculations (and assignments of other variables) involved in the assignment/evaluation of a variable (say, a getDegrees() of an Angle class that only stores radians internally).

If I find that some procedure done with a class involves a lot of modification of internal variables and is easily groupable into a single operation, I will put it into a function of the class rather than having the outside code call multiple smaller functions. However, I will not always enforce this in the interface by making the affected variables private instead.

Am I violating any principles by doing this? If so, how severely? The code that does this usually doesn't face outward, as I pay a lot of attention to how out-of-program input is processed.

答:
I'm working in a code base that sounds a lot like how you're programming. It's fairly awful. When you're in college (as I was recently) these principles don't make as much sense, because they're simply asserted to you. All of your assignments are going to be very small compared to real-world applications, however, and they will rarely get a chance to become complex enough to the point where they become difficult to handle.

This notion is a worrisome:

I sometimes leave internal class variables public if they are intended to be directly modified at some time

When working on small projects, it sometimes seems more convenient to let your member variables be altered by outside classes. This is almost always a bad idea. The more internal variables you allow the external program to alter, the less well you can reason about the state of your class at any given point in the program.

This kind of design is indicative of a bad object model. If you're finding that you have a class with variables that need to not only be read, but also written to frequently by other parts of the program, chances are those variables aren't logically a part of that class.

In my experience, the best kind of class to work with is one that is almost, if not totally, immutable from the outside, and only allowed to make changes to itself internally. Even better if it never changes once it's created.

Remember that not every variable needs a getter and setter. You should avoid writing either one entirely until you find out you absolutely must have them. Getters will almost always be more common than setters.

Title: How important is encapsulation?


问:
Algorithm to detect a CLICK within Square range
It might be a simple question but I am looking for optimal solution. I will have numbers printed on a screen and I will be aware of coordinates. Numbers/Symbols will have 4 points(Square) to define their boundaries. Coordinates of that particular symbol will be stored in a file. Lets' say there is a number 5 and it's 4 coordinates on screens are:(2,20,20,20,2,40,20,40)

Now lets assume that a string 555 represent a value in a file, say the value is Car1

When the user press num pad of 5 thrice then it should detect that he needs Car1.

I am interested to know whether there's some standard formula/Algo to find the range between these 4 coordinates or I have to work on my own. The Formula that was coming in my mind is:

Symbol = (X1+X2+X3+X4)(Y1+Y2+Y3+Y4) = (62)(120) = 182(Representing 5)

But I am skeptical whether it's right and whether the formula will always be given a unique value per symbol/character based on given coordinates?

答:
A common way to do this is just to compare the coordinates of the mouse click with the coordinates of the square.

Suppose the square has top-left coordinate of x1, y1 and bottom-right is x2,y2.

A mouse click at mx, my is in the square if (mx>x1 and mx<x2 and my>y1 and my<y2).

If all the square are the same size and in a grid, you can give each square a number:

n = y * number of squares in a row + x.

Then to get n from a mouse click:

n = (width of grid in pixels / square width in pixels * number of squares in a row) + (height of grid in pixels / square height in pixels)


问:
How can I become better on explaining the code to other developers?
While the question itself might sounds silly, the answer is quite important to me,
as I feel that issue is negatively affecting my work performance.

A bit of the background here: I am a seasoned senior software developer in a medium size
software department of non-software company. While being above average on the technical side of the things,
I am much poorer on communicating and explaining things. Even when explaining something to other developers.

The most difficulties happen when I explain how a particular small piece of code works.

The funny thing is, that explaining and providing examples on how something works on a much higher level,
e.g. interactions between separate modules and subsystems, is much easier for me.

To make it clearer, what I call "source code explaining skill" is a

a) ability to clearly explain the execution flow of the code - e.g. "this thingy calls that thingy, which returns that object, which is later calls method A, passing
the object B to ..."

a) ability to clearly explain the problems with a current design, or, which is more important, implications of the source code change as in "if, for performance
reasons, we start caching the object as a field of the class, we would have to make modification in ten different places to ensure that the cache is always
in up to date state" etc

I tried to analyse why I am bad on explaining things and haven't found any explanations except maybe that I explain things in a bullet points manner,
which some may find too rigid. Also when I explain things I perhaps focus too much on what I say myself and missing the questions, what people ask,
but again to me it feels like these questions are often irrelevant and simply draggin the conversation away.

What could you recommend (except the obvious "practices which makes it perfect", which I don't really buy, as
I think I would probably practice more of the same mistakes again and again) me to do, so I could improve the source code
explaining skills.

答:
The reason is simple.  You think like a programmer.

Being able to explain concepts at a high-level is what we do all our lives when we want to convey ideas.  However, when we program, we put ourselves in the mindset that we must understand how to do tasks in terms of many small and detailed steps.  Explaining that means you have to convert "small and detailed steps" to something anyone can understand, which is no small order.  If such things were easy to grasp, everyone could program.  That's what makes us programmers.

However, as you've probably guessed, it's one thing to understand how to do tasks in terms of many small and detailed steps and it's quite another to explain them well.

I, too, have had some difficulty in this endeavor but I've noticed that some tricks have helped me.  Assume you have a method that you've written and you must explain how it works:

Before you start with the first line, read your method and remember what the scope is, what purpose it serves, when it is called, and why this was how you decided to do that.  In short, know what it does.  In this way, you can answer questions in a thorough fashion and in a way that encompasses the sense of the method (i.e. when they say "I don't understand the point of this line", you can reply, "This is what instantiates the connection to the database used throughout the program" rather than "That calls the JDBC which uses the connect string to establish a connection" which answers the question but is probably not what makes it clear).

Explain each line in the method in terms of what each line contributes to the overall purpose of the method.  Why did you put that line there?  Oh right, this line calls the class responsible for taking care of input management in order to check if I needed to delegate actions in my render loop.

Admit when your code is perhaps unclear or could be improved.  If you find code that may be unclear, rewrite it in order to make it clearer.  It doesn't help communication to frustrate your fellow programmer into thinking that he should be understanding what he's seeing.

In general, focus on why you put that code there rather than what it does, and you'll find that your explanations will flow more easily and they will be easier to understand.


答:
I have also found myself in a similar position at times struggling with the explanation of the execution flow of code at a low level.  What helped me was to pick up the programming language guide in question (Bjarne Stroustrups Programming in C++) to refresh myself as to the terminology that had inevitably faded over the years.  Plus reading new language relevant articles/blogs to keep up to date with current techniques/terms.

Regarding complex design problems/implications: It is ok to say 'I can't give you an answer without doing more analysis' without giving an immediate answer.  Software can get very complex and even the smartest developers can't keep all the interactions in their head all the time - plus we are all human and get things wrong or miss things.

Take time to go away and analyse code so that you can be more sure of your answer. It would certainly be better than giving an immediate, possibly misinformed and wrong answer.  From a senior developers position it would be seen as wisdom and go in your favour instead of looking responsive but potentially foolish!

Title: How can I become better on explaining the code to other developers?

Body:
While the question itself might sounds silly, the answer is quite important to me,
as I feel that issue is negatively affecting my work performance.

A bit of the background here: I am a seasoned senior software developer in a medium size
software department of non-software company. While being above average on the technical side of the things,
I am much poorer on communicating and explaining things. Even when explaining something to other developers.

The most difficulties happen when I explain how a particular small piece of code works.

The funny thing is, that explaining and providing examples on how something works on a much higher level,
e.g. interactions between separate modules and subsystems, is much easier for me.

To make it clearer, what I call "source code explaining skill" is a

a) ability to clearly explain the execution flow of the code - e.g. "this thingy calls that thingy, which returns that object, which is later calls method A, passing
the object B to ..."

a) ability to clearly explain the problems with a current design, or, which is more important, implications of the source code change as in "if, for performance
reasons, we start caching the object as a field of the class, we would have to make modification in ten different places to ensure that the cache is always
in up to date state" etc

I tried to analyse why I am bad on explaining things and haven't found any explanations except maybe that I explain things in a bullet points manner,
which some may find too rigid. Also when I explain things I perhaps focus too much on what I say myself and missing the questions, what people ask,
but again to me it feels like these questions are often irrelevant and simply draggin the conversation away.

What could you recommend (except the obvious "practices which makes it perfect", which I don't really buy, as
I think I would probably practice more of the same mistakes again and again) me to do, so I could improve the source code
explaining skills.


问:
Is there any taxonomy/language to describe user interfaces?
I'm currently researching the options which I have, to build an 'Online Help System'. This system should offer the user information about dialogs - which consists mainly out of forms.

So my main question is: Is there any taxonomy/language to describe user interfaces?
I have searched a lot on this subject matter, but end up with things like XUL. Which is not what I'm looking for. I'm looking for a structure / language / taxonomy to describe the user interface (of the dialogs). However, I'm not sure of its existence. Since I'm not, I would also be pleased with any (search) terms which are worth investigating in this case.

Besides this, I'm also looking for languages / taxonomies which are used for regular Online Help systems. The things I came across were: DocBook, DITA and MAML. Are there any other big players in this 'market'?

答:
Microsoft's Glossary of UI Terminology

http://msdn.microsoft.com/en-us/library/windows/desktop/bb226821(v=vs.85).aspx

Is the closest thing I can think of.  If you're writing documentation for end users, you need to use industry-standard terms and simple, clear language.  A taxonomy sounds like some sort of hierarchical categorization of elements, which is something the end user neither needs nor is interested in.


答:
One of the problems is that small pieces of code don't always explain the bigger picture. For example, when I look at unfamiliar source code in a familiar programming language I usually understand most of the individual statements. At the same time, I may struggle to understand the unfamiliar algorithm to which they contribute, what role that algorithm plays in the complete solution and why that algorithm was chosen over other alternatives. In a sense, although I understand those statements, I really don't understand them at all.

An example of this is the classic Fast Inverse Square Root function.

Some things I find useful in dealing with this:

Explain the code in the same language the users use.

Explain the code using standard programmer terms, e.g. Terms like "buffer", "list", "singleton" are familiar to most of us, as are common mathematical terms.

Explain what you're doing in terms of the inputs and outputs.

Invent words for concepts you don't have words for. Sometimes I use words like "adjuster", "chain" or "wrangler" as a short-hand for some very knotty concepts. That is, after all, how well-known terms got invented in the first place.

Recognise that, although the few lines of code might appear simple in themselves, their role in a larger code base might be quite complex. You can't always explain them without providing a lot of background information. If that's the case, provide it.

Give concrete examples.

Draw diagrams.


答:
One of the advantages of using getters and setters (or properties) rather than public fields is that the logic can change without having to change the consumer. Right now you might only need to simply read and write to/from a variable, but what about in the future?

For example, in your Angle class, what would happen if you decided that from now on you want to store the angle as degrees rather than radians? You would now need a getRadians() method that does the appropriate calculation, and all the code that accessed Angle.radians directly would need to be changed to use this new method. On the other hand, your getDegrees() method could still be used. All that would need to change is its implementation.

If you'd used both getRadians() and getDegrees() methods to begin with, this internal change (from radians to degrees) would not concern the object's consumers at all - its public contract stays the same.

One of the principles of encapsulation is that the internal representation of an object should not concern its consumers.

Title: How important is encapsulation?

Body:
As a student in programming, I learned that encapsulation is one of the most important principles of object-oriented programming.

However, I only follow that principle when I feel like it suits my purpose. I sometimes leave internal class variables public if they are intended to be directly read at some time, and only use things like setters and getters when there are actual calculations (and assignments of other variables) involved in the assignment/evaluation of a variable (say, a getDegrees() of an Angle class that only stores radians internally).

If I find that some procedure done with a class involves a lot of modification of internal variables and is easily groupable into a single operation, I will put it into a function of the class rather than having the outside code call multiple smaller functions. However, I will not always enforce this in the interface by making the affected variables private instead.

Am I violating any principles by doing this? If so, how severely? The code that does this usually doesn't face outward, as I pay a lot of attention to how out-of-program input is processed.


问:
Why isn't Java being used for web multimedia applications?
I've been focusing on multimedia applications and I've noticed that most applications don't use Java in the back end. Instead, I see solutions with PHP/ROR/Python and Flash/Silverlight without any trace of Java in the application stack.

What part of Java is either limiting or constrained - or perceived as limiting or constrained - when building multimedia applications?

Let me clarify, when I said Java, I meant Java EE. Of course on the client side people will use flash or html5 for audio/video. But what I am trying is that, why is most multimedia platforms backend is created with PHP/ROR/Python(Django)? There are many audio distribution platforms out there. soundcloud.com (uses go lang), tunrtable.fm (uses Python) youtube.com (uses PHP), is Java EE not capable of doing those?

答:
I think all you have to do is look at the industry all around and you'll see the same pattern. PHP, Ruby, and Python are the preferred languages these days for building web applications. This is largely due to their interpreted nature and low barrier to entry (compared to Java) making development fast, easy, and cheap. This makes it ideal for somebody to hit the ground running when they have an idea.

Java EE is absolutely capable of handling the same tasks as any of those languages, whether the application is multi-media or otherwise. Java however, is compiled, verbose, and expensive (developers). This makes it not an ideal solution that everybody runs to when they want to rapidly prototype something. Java's limelight has been in the enterprise where companies are willing to shell out hundreds of thousands for developers, who quite honestly, are *usually better trained than the majority of PHP devs.

*= That's not to say that PHP devs are untrained, but rather by sheer numbers and barrier to entry means you'll encounter a lot MORE untrained/undertrained PHP programmers that you have to weed through. (Source: the last company I worked at was looking for an additional full time PHP dev. We interviewed a lot of amateurs.)


答:
When documenting user interfaces for an end user, the most important guideline is to use terminology that's consistent for your platform.  All of the major platforms have human interface guidelines (HIGs) that describe user interfaces and (in some cases) spell out what terminology to use in referring to user interface elements in end user documentation:

Windows User Experience Interaction Guides ("Windows UX Guide")

OS X Human Interface Guidelines

iOS Human Interface Guidelines

GNOME Human Interface Guidelines

Android User Interface Guidelines

More broadly, there are discussions of user interface patterns.  These kinds of taxonomies or patterns are more useful for designing your UI than they are for describing it to an end user, but they might at least give you some ideas.

Designing Interfaces, by Jennifer Tidwell

Quince

Yahoo! Design Pattern Library

Regarding online help systems, DocBook and DITA are the two main standards for writing documentation that I hear about.  There are also software programs like RoboHelp and Help & Manual that can create online documentation.

Body:
I'm currently researching the options which I have, to build an 'Online Help System'. This system should offer the user information about dialogs - which consists mainly out of forms.

So my main question is: Is there any taxonomy/language to describe user interfaces?
I have searched a lot on this subject matter, but end up with things like XUL. Which is not what I'm looking for. I'm looking for a structure / language / taxonomy to describe the user interface (of the dialogs). However, I'm not sure of its existence. Since I'm not, I would also be pleased with any (search) terms which are worth investigating in this case.

Besides this, I'm also looking for languages / taxonomies which are used for regular Online Help systems. The things I came across were: DocBook, DITA and MAML. Are there any other big players in this 'market'?


问:
Any tips to learn how to program with severe ADHD?
I have a difficult time trying to learn how to program from straight text-books. Video training seems to work well for me in my past experiences with PHP. I am trying my hardest to stay focussed and push through. Specifically I am looking to start indie game development.

Over the last two weeks I have been trying to pick the "right" language and framework to develop with. I started going through Python, but I am not really enjoying the language so far. I am constantly looking through this website to compare this language to that, and keep getting distracted.

Aside from all of this, is it possible to become a programmer when you have trouble focussing? Has anyone been through this that can recommend some advice?

答:
I have ADHD and this is what I do.

1.Deactivate Facebook and set SelfControl which is a distraction minimizing application for mac. There are other kinds too such as StayFocused for Chrome. I use SelfControl because, unlike StayFocused, it blocks selected websites from ALL browsers. You may not need that but I can be a little sneaky.

2.Use the Pomodoro technique (www.pomodorotechnique.com). Basically this just breaks your study/work time down into 25 minute increments with small breaks in between. This is a bit of a mind trick but for me it really works. It keeps me from getting too overwhelmed.

3.Find a quiet place and/or a good soundtrack. Sometimes I'll just listen to music without lyrics or with very few lyrics to drown out external distractions. This is all a matter of taste. I like to listen to Secret Agent or Space station on SomaFM.

4.Try to be as hands on as you can. Start a project to keep you going.

I've had a lot of trouble just picking a language. I think that's pretty common. A friend sent me an article, it was geared towards librarians learning code (although I'm not a librarian) and it said that the key is to just keep going. Often times people will get started and then change their mind and switch gears but you really have to just go with it. You can always learn another when you're done.


答:
The C++ RAII model gives you deterministic and automatic memory management (from the perspective of the library consumer). It's not exactly what you're looking for but it's a start. Although it is an opt-in design where you must explicitly choose to use it with smart pointers. Theoretically a library user could know nothing of memory management, and get the same automatic clean up as in Java.

Maybe a language with "forced" RAII could approach what you are looking for.

The determinism of RAII is nice because it allows you to apply the same technique for resources even more precious than memory. Such as connections and handles.

```<code>void foobar()
{
    //connections are even more precious than memory. A leak is bad news.
    Connection conn("foobar");
    conn.Open();
}//conn is automatically closed as it leaves scope. Memory is free too.
</code>```

Title: Deterministic and controllable fully automated memory management

Body:
Fully automated memory management increases productivity and integrity greatly, but usual implementation (GC) has a critical problem. It's non-deterministic, and not controllable. This causes many problems such as burst CPU load which is critical for realtime applications. Some kind of optimizations (incremental/concurrent GC) can reduce those problems but still non-deterministic and can't eliminate the problem completely.

I have been thought GC never can solve this problem, but recently, I learned and realized that GC operation doesn't need to be fully hidden. GC also can be deterministic and CPU burst-free by exposing some properly designed behavior controls.

I think (RC + manually invoked cycle detection) can do this. But this doesn't look efficient. Is there any better approach for deterministic and controllable fully automatic memory management implementation? Or can I get some link to example implementations?

Edit

I added these lines to make my question more clear.

deterministic and controllable in this context means user can track and run code at object creation and destroying explicitly. And also controls amount and time of memory management operation load.

fully automatic means it allocates and clears memory as like GC without extra concern.

Body:
The C++ RAII model gives you deterministic and automatic memory management (from the perspective of the library consumer). It's not exactly what you're looking for but it's a start. Although it is an opt-in design where you must explicitly choose to use it with smart pointers. Theoretically a library user could know nothing of memory management, and get the same automatic clean up as in Java.

Maybe a language with "forced" RAII could approach what you are looking for.

The determinism of RAII is nice because it allows you to apply the same technique for resources even more precious than memory. Such as connections and handles.

void foobar()
{
    //connections are even more precious than memory. A leak is bad news.
    Connection conn("foobar");
    conn.Open();
}//conn is automatically closed as it leaves scope. Memory is free too.


答:
There was a description by Butler Lampson in Hints for Computer System Design (Operating Systems Review 15, 5, Oct. 1983, p 33-48) of a system that combined both an incremental collector based on automatic reference counting and a trace-and-sweep collector that could clean up unreachable circular references. The idea is that an application could rely on the incremental collection to do most of the work, then do the "stop the world" garbage collection "used during coffee breaks to reclaim accumulated circular structures."

This was, according to that paper, implemented in the Interlisp-D and Cedar programming environments. It cites the following two articles that I haven't yet read but which—Lampson claims—describe the collector in more detail:

Burton, R.R. et al. Interlisp-D overview. In Papers on Interlisp-D, Technical report SSL-80-4, Xerox
Palo Alto Research Center, 1981.

Deutsch, L.P. and Bobrow, D.G. An efficient incremental automatic garbage collector. Comm. ACM
19, 9, Sep. 1976, pp 522-526.


问:
Why five dining philosophers?
I was wondering why the Dining philosophers problem is based on a five philosophers case. Why not four?

I guess that we can observe all unpleasant issues that can occur when discussing five philosophers example also when we are given four thinkers. Is it only for a historical reason then?

答:
Only Dijkstra can answer for sure but I would be confident enough that it's arbitrary.

"It was originally formulated in 1965 by Edsger Dijkstra as a student
  exam exercise, presented in terms of computers competing for access to
  tape drive peripherals. Soon after, Tony Hoare gave the problem its
  present formulation."

http://en.wikipedia.org/wiki/Dining_philosophers_problem

Title: Why five dining philosophers?


答:
When developing software for your own use, it's often to your benefit to use newer versions of your libraries and development tools.  However, the projects you're looking at are libraries and development tools meant to be shared with the community. In these cases, you want to be conservative in the features you require in order to get the broadest installed base & get the most people involved in the project.

The format() method wasn't added until the release of Python 3.0/2.6 in 2008.  That seems like a long time ago but keep in mind that people seldom use the first release of software.  Let's put this in context of when it became available in two of the more 'serious' Linux distros.  RHEL 5.x still uses Python 2.4 and is supported until 2017 - 6.x has Python 2.6 but that wasn't released until 2010.  In the Debian camp they didn't have Python 2.6 until the 6.x series which became stable in 2011.

So, while it might make sense, if you were starting a project like Django (originally released in 2005) today, to standardize on the new method, there's very little value in going back and changing all 1000 occurrences of the old method without it having been formally deprecated.  It makes work, creates the possibility of introducing bugs & needlessly increases the system requirements.


问:
idquantique .vs. rdrand
We are currently looking at using the idquantique random number generator device to provide random numbers.  There are some issues though.  We would only be using one device and we have at least 5 servers that would need to use it and this number will probably increase in the future.  This implies that blocks of random numbers would have to be sent to the servers in some way.  All the servers are running Linux.

All of our servers are Intel based and have the RDRand random number instruction available.  It would be easier to use RDRand since no networking calls would need to be made and RDRand also appears to be significantly faster.

But, the question I would like answered is - is there a difference between the quality of the random numbers generated by RDRand and those generated by idquantique?  Has anyone ever measured or tried to measure how well these two random number devices perform against each other?

答:
About the only way to answer this is to ask who you trust more.  IDQ makes the following statements.

from here.

Existing randomness sources can be grouped in two classes: software solutions, which can only generate pseudo-random bit streams, and physical sources. In the latter, most random generators rely on classical physics to produce what looks like a random stream of bits.

In reality, determinism is hidden behind complexity.  Contrary to
classical physics, quantum physics is fundamentally random. It is the
only theory within the fabric of modern physics that integrates
randomness.

If you trust IDQ's statements, then Intel's RdRand solution, being based in software using hardware entropy, is sub par.  However, even that might be good enough depending upon your particular usage.

Next, I'm not entirely sure why you would only use 1 device to generate numbers for multiple servers.  The quantis cards aren't terribly expensive.  Further, if what you are doing requires that type of randomness then it stands to reason that the money spent for cards for each server would be trivial to what you are doing.

However, if not, then you might just punt on using quantis and go with the built in Intel solution.

Title: idquantique .vs. rdrand


答:
IBM's Metronome garbage collector for the JVM is deterministic.  Basically, it runs continuously in parallel with the application.  You specify how much CPU time it can use, with lower CPU time values requiring a larger heap.  It isn't suitable for applications that do a lot of heap thrashing, but for typical applications it supposedly works well.

Azul System's C4 garbage collector for their Zing JVM appears to be similar, but I haven't seen any technical details about how it works, so I don't know if it's fully deterministic or not.


问:
Is LISP still useful in today's world? Which version is most used?
I try to teach myself a new programming language in regular intervals of time. Recently, I've read how Lisp and its dialects are at the complete opposite end of the spectrum from languages like C/C++, which made me curious enough to know more about it. However, two things are unclear to me, and I'm looking for guidance on them :

Is LISP still practiced/used in todays world, or is it a legacy language like FORTRAN/COBOL ? I mean, apart from maintaining existing code, is it used on new projects at all ?

What is the most widely used dialect ? I came across Scheme and Common Lisp as the 2 most prevalent dialects, and wanted your opinion as to which is the most favored/useful one to learn - and would be immensely gratified if you can suggest any resources for a rank beginner to start from.

While eager to learn a language which is fundamentally different from the procedural languages I'm used to, I don't want to invest undue effort in something if its totally obsolete - I'd still learn it if it was professionally "dead", but only with an academic perspective...

答:
I'd like to add some perspective about Common Lisp and Scheme. I've avoided clojure due to the JVM, so I don't have a lot of perspective on it.

Scheme is a beautiful concise, well defined language. It took a lot of decisions that CL had to make due to legacy, and took the more pure approach. For instance, variables and functions are in the same namespace. The default language is smaller and more concise, which works well for teaching you the sorts of things that lisp is good at, for instance it pressures usage of recursion instead of iteration, since it by default has no iterative loops, and requires tail call optimization. Scheme has a very interesting hygienic macro system, which there is much value to learning. But IMO, I would recommend learning CL-style Unhygienic macros first, of which most(?) scheme dialects offer at least one implementation of, even if it's not a part of the spec. Since it seems very much that you want to learn a language for learning's sake I'd recommend Scheme, since additionally, many of it's concepts are easily transferred to other lisps, and dynamic languages in general.

Having said that, Scheme's community is fragmented, and other than in a few small pockets, seems to be mostly dedicated to research over getting real work done... For instance every dialect has their own package manager, and packages are most often not portable across dialects, which is a huge problem in the scheme community.

Common Lisp on the other hand, seems to be the much more pragmatic approach to developing a language. The standard is such that much lisp code is portable between implementations, many compilers are fast and well-optimized. There is a large set of packages, many of which are portable between implementations. And seemingly a (comparatively) large amount of real products are getting created in the language. And with say quicklisp, it's package management feels reasonably close to what you'd get in a modern community like say Ruby, or Node. CL, is however not without flaws, it has a very large spec at this point compared to scheme, and even it's object system CLOS, something that is traditionally written as a library in Lisps, is part of the spec IIRC. And you can feel legacy entrenched through a large amount of the system. The standard build system approach of extracting an image for compilation feels particular arcane, for example.

Otherwise, I said I couldn't speak on clojure, and Emacs Lisp is clearly the appropriate choice if your goal is to write Emacs extensions, and pretty clearly not the appropriate choice for other software.

TLDR; If your goal is to learn, I recommend Scheme. However, if you want to create software, I'd recommend Common Lisp of the two major lisp variants.


答:
As I have learned more about OO Development, I've realized that an object with a lot of getters and setters isn't really an object...it's more of a struct.

People like to use real world examples to illustrate especially when talking to learners. So let's use an example that everyone can understand.

When a person is conceived, he (or she) is giving certain parameters that will form his or her appearance. Height, weight, skin tone, eye color, jaw structure, etc., etc are all determined at conception via DNA. Consider conception as a person's constructor, and the mother and father's DNA as parameters to that constructor.

There are some properties about the person that can be set after construction (such as his name and birthdate -- although, that is MOSTLY determined internally), but everything else can only be observed not changed (well except through surgery but you get my drift). Changes to a person's height occur internally...no one says "Michael, grow two inches" my body determine how much I grow based on the inputs is give it (food, rest, whether or not I smoke, and of course my DNA).

Complex objects in an application should be like this model of a human. We provide some parameters at construction. We can perform operations on it (or even it performs operations on itself), and observe the results of our input and its interaction with the rest of the system. But its core data should be immutable to the outside.

Even simple objects that have data and little logic should be immutable because they represent values. For example look at a string in C# once you initialize it, you can't change that copy of the string the same with Dates. Data sent between objects should be immutable or a copy of the original (C# supports this natively via Structs which are passed by value versus Classes which are held by reference).

Title: How important is encapsulation?


答: Basically, yes.  Software-based pseudo-random-number generators will always be inferior to true random-number generators that are based on observation of provably-random events.  I think the real question, though, is do you need absolute randomness, or is RdRand "good enough"?  If you're just generating random keys to ensure even distribution across a hash table or something similar, then you probably don't need absolute randomness.</p>

Title: idquantique .vs. rdrand

Body:
We are currently looking at using the idquantique random number generator device to provide random numbers.  There are some issues though.  We would only be using one device and we have at least 5 servers that would need to use it and this number will probably increase in the future.  This implies that blocks of random numbers would have to be sent to the servers in some way.  All the servers are running Linux.

All of our servers are Intel based and have the RDRand random number instruction available.  It would be easier to use RDRand since no networking calls would need to be made and RDRand also appears to be significantly faster.

But, the question I would like answered is - is there a difference between the quality of the random numbers generated by RDRand and those generated by idquantique?  Has anyone ever measured or tried to measure how well these two random number devices perform against each other?


问:
What is the most egregious waste of money you have seen, and what did you do about it?
Often we as programmers see large organisations wasting huge sums of money on bloated and inefficient solutions to problems. This pains me greatly because I like organisations to benefit from best of breed solutions. However, my abilities as a programmer are limited when it comes to influencing the key decision makers and often my perspective on the matter is constrained to my own little technical world.

So, my question is this. After encountering an egregious waste of money on some software and/or hardware that really got your goat, what did you do about it to get it fixed or were you doomed to bite the bullet and mutter forever under your breath? I'm interested in hearing your overall experiences and especially what lessons you learned about how to tackle this sort of thing in the future. Let's not name names, the experience of how to tackle the problem is more important than the actual offending product.

答:
Proprietary version control systems. Given the state of Git and Mercurial, I don't see why people would go for something with a gate keeper.

Not only do you have to pay for the VCS, you also have to pay per user. Additionally, your flexibility gets shot in the foot. You might as well wear a T shirt that says "I ♥ Vendor Lock In!!!"

I feel that it's just nuts these days to not use a free (D)VCS. If you want lots of add on perks to go with it, stuff like Kiln is available.

I don't think I'd go to work for someone that insisted on BitKeeper or similar.

I almost said the same thing about emulators, but products like Simics continue to offer significant advantages over free alternatives.


答:
Per what is written in EWD310 "Hierarchical Ordering of Sequential Processes", it looks like number 5 has been chosen for educational purposes, in order to make it easier for students to understand algorithm designed to demonstrate solution of the problem.

This very paper further supports the idea that 5 is not really relevant to general problem, first by explicitly stating that "the problem could have been posed for 9 or 25 philosophers..." and next, by representing it in terms of two concurrently operating entities, "class A and class B, sharing the same resource..."

Solution used by Dijkstra introduces three "states of philosopher": thinking, eating, hungry. Code presented to solve the problem, operates these three states, along with an unrelated to it number of philosophers.

Would author has chosen number of philosophers 2, 3 or 4, this could cause confusion of the students reading the code, whether chosen number is related to the amount of states or something else. This can easily be tested by trying mentioned numbers in description quoted from EWD310 below: note for example how this would change [0:4] to [0:3], [0:2], [0:1] and statements involving mod.

As opposed to this, number 5 looks fairly innocent and doesn't invoke unneeded associations. One can say that it has been chosen to better illustrate that amount of philosophers is, well, arbitrary.

Mentioned algorithm is presented in EWD310 as follows:

...we associate with each philosopher a state variable, "C" say, where

C[i] = 0 means: philosopher i is thinking

C[i] = 2 means: philosopher i is eating.

...

we introduce for the last transition an intermediate state

C[i] = 1 means: philosopher i is hungry

Now each philosopher will go cyclically through the states 0, 1, 2, 0 ...... The next question to ask is: when has the (dangerous) transition from 1 to 2 to take place for philosopher K?

...

In the universe we assume declared

1) the semaphore mutex, initially = 1

2) the integer array C[0:4], with initially all element = 0

3) the semaphore array prisem[0:4] with initially all elements = 0

4) procedure test (integer value K);

```<code>if C[(K-1) mod 5] ≠ 2 and C[K]= 1
    and C[(K+1) mod 5] ≠ 2 do
      begin C[K]:= 2; V(prisem[K]) end;
</code>```

(This procedure, which resolves unstability for K when present, will only be called from within a critical section).

In this universe the life of philosopher w can now be coded

```<code>cycle begin think;
            P (mutex);
               C[w]:= 1; test (w);
            V(mutex);
            P(prisem[w]); eat
            P(mutex);
               C[w]:= 0; test [(w+l) mod 5];
               test [(w-1) mod 5];
            V(mutex)
      end
</code>```

And this concludes the solution I was aiming at...

Title: Why five dining philosophers?

Body:
I was wondering why the Dining philosophers problem is based on a five philosophers case. Why not four?

I guess that we can observe all unpleasant issues that can occur when discussing five philosophers example also when we are given four thinkers. Is it only for a historical reason then?

Body:
Per what is written in EWD310 "Hierarchical Ordering of Sequential Processes", it looks like number 5 has been chosen for educational purposes, in order to make it easier for students to understand algorithm designed to demonstrate solution of the problem.

This very paper further supports the idea that 5 is not really relevant to general problem, first by explicitly stating that "the problem could have been posed for 9 or 25 philosophers..." and next, by representing it in terms of two concurrently operating entities, "class A and class B, sharing the same resource..."

Solution used by Dijkstra introduces three "states of philosopher": thinking, eating, hungry. Code presented to solve the problem, operates these three states, along with an unrelated to it number of philosophers.

Would author has chosen number of philosophers 2, 3 or 4, this could cause confusion of the students reading the code, whether chosen number is related to the amount of states or something else. This can easily be tested by trying mentioned numbers in description quoted from EWD310 below: note for example how this would change [0:4] to [0:3], [0:2], [0:1] and statements involving mod.

As opposed to this, number 5 looks fairly innocent and doesn't invoke unneeded associations. One can say that it has been chosen to better illustrate that amount of philosophers is, well, arbitrary.

Mentioned algorithm is presented in EWD310 as follows:

...we associate with each philosopher a state variable, "C" say, where

C[i] = 0 means: philosopher i is thinking

C[i] = 2 means: philosopher i is eating.

...

we introduce for the last transition an intermediate state

C[i] = 1 means: philosopher i is hungry

Now each philosopher will go cyclically through the states 0, 1, 2, 0 ...... The next question to ask is: when has the (dangerous) transition from 1 to 2 to take place for philosopher K?

...

In the universe we assume declared

1) the semaphore mutex, initially = 1

2) the integer array C[0:4], with initially all element = 0

3) the semaphore array prisem[0:4] with initially all elements = 0

4) procedure test (integer value K);

if C[(K-1) mod 5] ≠ 2 and C[K]= 1
    and C[(K+1) mod 5] ≠ 2 do
      begin C[K]:= 2; V(prisem[K]) end;

(This procedure, which resolves unstability for K when present, will only be called from within a critical section).

In this universe the life of philosopher w can now be coded

cycle begin think;
            P (mutex);
               C[w]:= 1; test (w);
            V(mutex);
            P(prisem[w]); eat
            P(mutex);
               C[w]:= 0; test [(w+l) mod 5];
               test [(w-1) mod 5];
            V(mutex)
      end

And this concludes the solution I was aiming at...


问:
Domain Services as facades
I read .NET Domain-Driven Design with C#: Problem - Design - Solution and I noticed that the author created a domain service for each aggregate root.

However, the domain services were only facades to the corresponding repository. For example this is a code sample from the application from his book

```<code>public static class CompanyService
{
    private static ICompanyRepository repository;
    private static IUnitOfWork unitOfWork;

    static CompanyService()
    {
        CompanyService.unitOfWork = new UnitOfWork();
        CompanyService.repository =
            RepositoryFactory.GetRepository<ICompanyRepository,
            Company>(CompanyService.unitOfWork);
    }

    public static IList<Company> GetOwners()
    {
        return CompanyService.GetAllCompanies();
    }

    public static IList<Company> GetAllCompanies()
    {
        return CompanyService.repository.FindAll();
    }

    public static void SaveCompany(Company company)
    {
        CompanyService.repository[company.Key] = company;
        CompanyService.unitOfWork.Commit();
    }

    public static Company GetCompany(object companyKey)
    {
        return CompanyService.repository.FindBy(companyKey);
    }
}
</code>```

As you see almost all calls to the services are wrappers to repository calls. Is this a good pattern when building domain services?

Should we always wrap our repositories in domain services? Is there a better approach?

答:
A repository is meant to be an abstraction for your data store, and generally provides data-retrieval capabilities.  This arrangement allows you to, for example, change out the data store for some different datastore (say, from Oracle to SQL Server, although in practice this rarely happens), and your repository API should still work, if you didn't expose any implementation-specific details.

A service layer, on the other hand, is an API meant to be consumed by some outside user or agent, and provides services, not data retrieval per se (although it can do that).  A Service API might draw on multiple repositories, and perform transforms on the data before serving it to the client.  It might wrap the data into custom objects, or provide paging abilities.  You can do things in your service layer beyond simple data storage and retrieval.

If you don't have the need to provide an additional layer of abstraction beyond what your Repository provides, you might not need a Service Layer at all.

Title: Domain Services as facades


问:
PHP OOP: Should every object contain all the data?
I'm trying to learn PHP OOP "properly", and I was wondering, should the constructor grab all the information in the database and store it in the object?

To use an example I'm trying to create using PHP OOP, an internet comic website (much like XKCD's), would have two classes:

Catalogue (list and order of all the episodes)

Episode (data relating to that particular episode)

So, in this situation, should the Catalogue object get an array of all the episodeIDs (presumably this would be gotten in the constructor)? And if so, does that mean I have to update both the Object's array and the Database's array? And if so, what's the most common way of implementing this (presumably very common) action?

答:
There are a few different approaches you can use to do this, depending on the data set, performance needs, and your general preference.

If there's an object that is used almost exclusively for display, you would probably want to query the dataset beforehand in some sort of Factory and then create the object by passing the data into the constructor.

If there's an object that touches a bunch of data sources and is used for different things, loading all of the data at instantiation might take a long time, and all of the object's data might not be needed every time that object is instantiated. You can leverage lazy loading to accomplish this goal.

If performance is a major concern, and the object stores a ton of data but is mostly immutable, you can use something like the Flyweight pattern, which allows you to actually treat a single object like a collection.

I highly recommend you try a few different ways of doing things. For a project such as yours, how you choose to instantiate and populate the object will probably matter little, but it will be a good and fun exercise in different object instantiation patterns.

As a final note, much of the knowledge you're gaining now about OOP can be applied to nearly any language you learn in the future.


答:
All memory management systems have their trade-offs. As DeadMG's answer points, you can't have everything.

Here's a quick guide to some of the trade-offs you can make, and some of the things you CAN have.

Note this isn't necessarily comprehensive, but it's a starting point on thinking about memory allocation/deallocation strategies.

1) Full bore manual - the nadir of determinism.

Upside: You decide when each piece of memory goes away. You'll never get paused by a garbage collector!

Downside: You've GOT to do all the accounting for used memory your own self. And you're likely to screw it up at some point, especially if you try to handle the cases where you need more memory and want to recover it from another part of your program on the fly.

Implemented in: C is the poster child for this one.

2) Deallocate on last reference drop

Upside: You can generally see where deallocation is going to happen, and plan for it appropriately. Since references are automatically cleaned up appropriately, you won't accidentally lose memory. If you've got compiler support, you simply can't screw up and lose memory.

Downside: If you forget or don't realize that you're dropping the last reference to a massive data structure, you can take a big hit at an inappropriate moment.

Implemented in: Perl 5, if I'm not mistaken. Also, if you use it correctly, you can emulate this in C++, though since there's no compiler forcing of it, it's not as safe.

3) Full-on GC

Updside: You don't have to deal with it. Ask for objects, they show up and get cleaned up when you're done with them. Eliminates all the hassle of accounting for memory - if there's free memory, you're good to go! By doing the deallocation in bigger chunks, this also reduces the total cost of the deallocations. If you do a lot of create/delete, that can actually be a good savings.

Downside: The garbage collector may end up locking the heap for extended periods of time. How long is a function of the implementation, but it's going to be larger than any single deallocation. More complex GC algorithms lock for less time, but at the cost of increased complexity. In general you can't do useful work based on object destruction, because the objects may well get destroyed at a time MUCH later than when it's last been used (No RAII for you).

Implemented in: Java's the GC platform I'm most familiar with. Older versions of Java had less capable GCs and bogged down a lot. Modern Java doesn't do this much unless you're doing something pathological.


答:
As your application grows, there are complex operations that your service layer can wrap and expose. It's really a facade over the domain model. For instance in a sales app, you might not care about the line item as a discrete object within the model. You just want to add items to a cart, check them out, and print an invoice for the user after any discounts are applied.

Behind the scenes there are probably dozens of objects involved in the interaction. The service might project a flattened view of the object model so that as the domain model changes behind the scenes, the client is not impacted by those changes.

Title: Domain Services as facades

Body:
I read .NET Domain-Driven Design with C#: Problem - Design - Solution and I noticed that the author created a domain service for each aggregate root.

However, the domain services were only facades to the corresponding repository. For example this is a code sample from the application from his book

```<code>public static class CompanyService
{
    private static ICompanyRepository repository;
    private static IUnitOfWork unitOfWork;

    static CompanyService()
    {
        CompanyService.unitOfWork = new UnitOfWork();
        CompanyService.repository =
            RepositoryFactory.GetRepository<ICompanyRepository,
            Company>(CompanyService.unitOfWork);
    }

    public static IList<Company> GetOwners()
    {
        return CompanyService.GetAllCompanies();
    }

    public static IList<Company> GetAllCompanies()
    {
        return CompanyService.repository.FindAll();
    }

    public static void SaveCompany(Company company)
    {
        CompanyService.repository[company.Key] = company;
        CompanyService.unitOfWork.Commit();
    }

    public static Company GetCompany(object companyKey)
    {
        return CompanyService.repository.FindBy(companyKey);
    }
}
</code>```

As you see almost all calls to the services are wrappers to repository calls. Is this a good pattern when building domain services?

Should we always wrap our repositories in domain services? Is there a better approach?


答:
It is possible to write in C / C++ your own memory manager, that meets the needs for your project.  I have seen this done to solve the memory management bottleneck in a server application that had huge numbers of threads with each thread making and destroying large numbers of small objects.  This app's performance was limited by a critical section in the memory manager, and was solved by threads grabbing much larger blocks of memory and managing their own objects.

It is also possible to create an application in C/C++ that largely avoids using the heap for memory allocation. The application creates large fixed size arrays of objects at start up, so then only uses indexs to the array of that object type.  I believe that this was a strategy in some big name computer games back in the 1990's. It completely elminiates the problem of memory fragmentation, and with threads having their own cache of index numbers they can use, it reduces contention memory allocation.


问:
FizzBuzz - really?
When it comes to "interview test" questions, the subject of FizzBuzz often comes up. There is also a Coding Horror post about it.

Now, if you bother reading sites such as this, you are probably less likely to be in the demographic of programmers who would find FizzBuzz anything but trivial.

But is it really true that 99% of programmers will struggle with it?

Really?

What is the evidence to back this up?

Some real-life examples would be very helpful in answering this question.

答:
I was recently tasked with interviewing over 50 programmers for a senior position where they would be working mostly with PHP.

I tossed the fizzbuzz problem on the screening exam, mostly to amuse myself and because I wanted ten good questions and had only nine. My intent, at the time was to show people that we can have fun too, even on interview questions.

80% Of the applicants solved the problem, but did not use the modulus operator.

15% of the applicants could not solve the problem.

5% of the applicants solved the problem using the modulus operator.

While my sampling is quite limited (50 applicants from one country), I can tell you that:

95% of them had a BS or higher in a CS curriculum (universities here compete by trying to make CS sound more spectacular).

I was truly amazed. Well, frightened .. but amazed. I did not think I'd come close to reproducing the results, since the problem has become so popular. This shows me that 5% of my applicants might not be super programmers, but at least they read programming related blogs.

Title: FizzBuzz - really?


问:
Are there any good reasons to use, learn, or recommend XSLT?
I am a developer for the last 8 years. We used XSLT primarily to transform XML into HTML. We also used it for XML to XML transformation.

But we have replacement for everything now. HTML can be comfortably created through programming languages such as ASP.Net. XML can be read and manupulated in any standard highlevel languages. As programming in XSLT is a little complex, any one would prefer working on latest programming languages.

Now my question:
Will XSLT be a significant choice in future, not considering the fact of maintaining already developed XSLT? Can I recommend new programmers to study XSLT?

答:
XSLT is pretty much dead because only a few enthusiasts still use it. However, there is no real alternative for it. If you focus only on a single use case, such as for example rendering of HTML pages from semantic documents, you find better tools. If you look for code generation template engines, again there is better tools. The same for document transformation.

But if you look for a tool that supports all these use cases pretty well on all platforms, then choices get very limited. If you already have an XML document and would have to transform it to something to be able to use your tool, you're probably better of just processing your data with XSLT (or XQuery).

Either way, you can learn XSLT in a matter of days, maybe weeks. It won't hurt you to make a first hand experience. Just give it a shot. It's at least worth the effort to store this kind of pattern (rule based transformations) in your head for later use. This alone justifies learning XSLT.