问:
Convert to Object Oriented Programming
I am currently working on a project that is fairly small for the time being.  There was a recent change to implement 3-tier architecture, such that the code is now split up appropriately to data access, business logic and user interface tiers.  However, there is no use of objects outside of creating them to ultimately call a data access method.

At a very basic level, pretty much everything we do is:

```<code>    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Dim dt As New DataTable
        dt = objBl.GetSomething
        'Assign to Grid
        'Format Grid
    End Sub
</code>```

I want to implement something more like:

```<code>Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    Dim lstSomeObject As New List(Of SomeObject)
    'Populate list of objects by calls to business layer
    DataGridView1.DataSource = lstSomeObject
    'Format Grid
End Sub
</code>```

Ultimately, not much different.  But instead of us having to pass thirty variables through to get a resultant data table that is used once, we could create an object (and lists of objects) and pass these around instead.  I have a couple years experience working in such an environment, but zero experience in converting to such an environment.  Frankly, I am at a loss as to how to do this.

Do I create a separate entities project for this, and then does everything reference this?  Or do I force our current objects to store both the properites and methods for each object type (this way feels counter-intuitive to me)?  Or something else entirely?  I have searched around most of the weekend and have not found anything overly helpful.

答:
It sounds like you're describing a data transfer object or more commonly known as a DTO.

The biggest advantage of a DTO is just as you said - avoiding having to pass around 30 variables.

Using DTOs is a good first step for moving into a n-tier architecture which is sounds like you may be trying to achieve.  An n-tier architecture takes advantage of several OOP principles such as encapsulation in order to make your overall application more maintainable.

Do I create a separate entities project for this, and then does everything reference this?

Yes, that's generally the easiest way and cuts down on duplicated code.  Your layers that access the DTO may have to test for a valid value, but that's about the worst of it.

Title: Convert to Object Oriented Programming


问:
How to alter the code at runtime in an interpreter?
While reading the difference between Compiler and interpreter , I found the following differences fromt he internet.

Advantages of using compiler:

Since compiler converts the program to native code of the target machine (object code), faster performance can be expected.

There is a scope for code optimisation.

Advantages of using interpreter:

Process of execution can be done in a single stage. There is no need of a compilation stage.

Alteration of codes possible during runtime.

Really useful for debugging the codes (because source code execution can be analyzed in an IDE)

Facilitates interactive code development.

In case of interpreter, stated as interpreter "there is a possibility of alter the code" and

In case of compiler "code optimization will be there"

Can anyone explain these 2 points ?

答:
tl;dr: Once upon a time, there were compilers, and there were interpreters, and each could be clearly identified. Now, most compilers and most interpreters are somewhere in between.

Not all compilers compile to native code - e.g. Java

Many interpreters are actually compilers behind the scenes (Perl, Python etc.) and so can do the same optimisations

Alteration of code is done, in my experience, more in compiled code than in interpreted code; both at compilation time (e.g. C's #ifdef) and very occasionally in binary code (very specific optimisations, or to hide what the code is doing). Compilation time stuff is very, very common, binary code is very, very rare.

Compiled code usually contains a symbol table, so you can find out what line in the source code a piece of compiled code corresponds to.
Facilitates interactive code development.

Altering code at runtime (which can, actually, be done both by an interpreter or compiled code) is a very dubious strategy, and error prone. I have seen it done in compiled (assembly) code more than interpreted code, and it tends to be a very small piece of code, which is VERY time critical, or for DRM purposes (where the author of the code does not want you to be able to figure out what he's doing). I've also seen it done for very, very wrong reasons.

As for "interpreted" code, most modern "interpreted" languages do "just-in-time" compiling - that is, when you run the code, the "interpreter" compiles the code (often into bytecode), and so can (and do) do code optimization too. In some cases, the compiled code is even cached, to be reused if the source file is not changed. An example of this is Python, which stores compiled bytecode in .pyc files.

Not all compilers compile to native machine code; java, for example, is compiled to java bytecode, to be run by the java virtual machine, which, in a way, is an interpreter. To confuse things further, some java virtual machines are themselves "just-in-time" compilers. Some even compile bytecode used frequently, and interpret the rest.

ContentLicense: CC BY-SA 3.0


问:
Git commit not finished but can't continue on that machine
Sometimes I run into the problem of having uncommitted code on a workstation that is not ready for a commit but needs to be completed on a different workstation or laptop.

Does anyone have a solution for this problem, such as a "soft commit" or some other way of transferring the changes to another machine to work on them elsewhere?

I would prefer not to be forced to commit and push changes that are not properly implemented.

答:
You can use git diff to create a patch and then apply it on other machine. Or you can create a temporary commit, then pull it from other machine. You can even create a temporary branch on some other machine, push your temporary commit there, then delete the branch.

My favorite method is the second one: creating a temporary commit, then going to another machine and doing something like this:

```<code>$ git fetch ssh://first_machine/path/to/repo whatever_branch_i_was_working_on
$ git reset --hard FETCH_HEAD
$ git reset HEAD^
</code>```

Body:
You can use git diff to create a patch and then apply it on other machine. Or you can create a temporary commit, then pull it from other machine. You can even create a temporary branch on some other machine, push your temporary commit there, then delete the branch.

My favorite method is the second one: creating a temporary commit, then going to another machine and doing something like this:

$ git fetch ssh://first_machine/path/to/repo whatever_branch_i_was_working_on
$ git reset --hard FETCH_HEAD
$ git reset HEAD^


问:
How to commit in-progress refactoring?
So, I have this big project, which is in the process of being refactored by me. I am changing a lot of stuff, so there is no chance to get it to compile some time soon. I am living in a special git branch which I named cleanup (which is going to get merged into master eventually, of course).

The problem is, that I/we have the policy to never commit non-compiling code (ideally it should also work, but it must compile and link, at the very least). So, until I am finished with this huge task, I am unable to commit anything (for review or for bookkeeping).

This is not the way I like to work (I believe most people commit at least once a day or so).

What do you think? Is there a solution I am overlooking?

Can I later tell git to aggregate commits or something? I could live with non-compiling commit as long as they stay in the cleanup branch.

Edit

To the subject of pushing/committing: I am aware that it is a huge difference, but later, there will be broken revisions, when I merge my stuff into master. So if you browse through the history (or git bisect ...) then the "local" revisions will be world accessible. So only committing locally and not pushing is not the best solution, because it will cause you trouble later on (when the subject is closed and forgotten for some time).

In short: Local commits will be pushed eventually. The global history should not show non-compiling commits.

答:
A rewrite is not a refactoring

I realize you're interested in how to use Git, but I would argue that you should consider changing the way you do refactorings more than the way you use Git (although I do think Git can help you).

Martin Fowler defines refactoring as:

a disciplined technique for restructuring an existing body of
  code, altering its internal structure without changing its external
  behavior.

Its heart is a series of small behavior preserving transformations.
  Each transformation (called a “refactoring”) does little, but a
  sequence of transformations can produce a significant restructuring.
  Since each refactoring is small, it’s less likely to go wrong. The
  system is kept fully working after each small refactoring, reducing
  the chances that a system can get seriously broken during the
  restructuring.

If you apply this method you can commit (and push) on a regular basis.

You might argue that this is impractical, and that it doesn't work for something large scale. This is where the Mikado method can help. You decompose a large refactoring into a series of small refactorings by creating a dependency graph. The method is recursive, try to make your change, it doesn't break anything check it in, otherwise revert your change and make a note of the pre-requisites. One by one, you fix those pre-requisite refactorings until you can achieve your main refactoring goal.

Git can really help this method. You can keep your local (broken) branch. As you commit (and push) the sub-goals you can rebase your main goal branch to on top of the commits you've just made, until it is no longer broken.

Title: How to commit in-progress refactoring?


问:
Disadvantages of scoped-based memory management
I really like scope-based memory management (SBMM), or RAII, as it is more commonly (confusingly?) referred to by the C++ community. As far as I know, except for C++ (and C), there's no other mainstream language in use today that makes SBMM/RAII their main memory management mechanism, and instead they prefer to use garbage collection (GC).

I find this rather confusing, since

SBMM makes programs more deterministic (you can tell exactly when an object is destroyed);

in languages that use GC you often have to do manual resource management (see closing files in Java, for example), which partly defeats the purpose of GC and is also error prone;

heap memory can also (very elegantly, imo) be scope-bound (see std::shared_ptr in C++).

Why is not SBMM more widely used? What are its disadvantages?

答:
One major advantage of a GC system which nobody has mentioned yet is that a reference in a GC system is guaranteed to retain its identity as long as it exists.  If one calls IDisposable.Dispose (.NET) or AutoCloseable.Close (Java) on an object while copies of the reference exist, those copies will continue to refer to the same object.  The object won't be useful for anything anymore, but attempts to use it will have predictable behavior controlled by the object itself.  By contrast, in C++, if code calls delete on an object and later tries to use it, the entire state of the system becomes totally undefined.

Another important thing to note is that scope-based memory management works very well for objects with clearly-defined ownership.  It works much less well, and sometimes downright badly, with objects that have no defined ownership.  In general, mutable objects should have owners, while immutable objects don't need to, but there's a wrinkle: it's very common for code to use an instance of a mutable types to hold immutable data, by ensuring that no reference will be exposed to code that might mutate the instance.  In such a scenario, instances of the mutable class might be shared among multiple immutable objects, and thus have no clear ownership.


问:
.Net Best Practices : Common Bugs Introduced By Refactoring, Carelessness, and Newbies
What are the common bugs introduced by refactoring, carelessness, and newbies?

I would like to request the experienced programmers here to share their experience and list the bugs they used to introduce when they were inexperienced.

In your response, please write a headline mentioning the kind of bug in bold text, followed by few linebreaks, and then an explanation, cause of the bug, and finally the fix.

答:
INotifyPropertyChanged bug introduced by refactoring, misspelling, case-mismatch etc.

Sometimes we change the name of some of our properties, and we forget to change the "string" we pass toOnPropertyChanged() method (especially when we call this method from somewhere else), or simply misspell it, including case-mismatch.

Something like this:

```<code>public string FirstName //earlier it was simply 'Name'
{
      get { return m_name; }
      set
      {
          m_name = value ;
          OnPropertyChanged("Name"); //still 'Name'. Bug!
         //or, OnPropertyChanged("FirstNane"); //changed, but misspelled. Bug!
      }
}
</code>```

Fix

```<code>protected void OnPropertyChanged(string propertyName)
{
   //this raises exception if there is something wrong (only in debug mode!).
   RuntimeAssert.ValidatePropertyName(this, propertyName);

   //your code here
}
</code>```

Here is the implementation of RuntimeAssert class.

```<code>   public static class RuntimeAssert
    {
        private static Dictionary<Type, List<string>> ClassPropertyMap = new Dictionary<Type, List<string>>();
        private static List<string> GetProperties(Type type)
        {
            if (!ClassPropertyMap.ContainsKey(type))
            {
                PropertyInfo[] props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                ClassPropertyMap.Add(type, new List<string>(props.Where(p => true).Select(p => p.Name)));
            }
            return ClassPropertyMap[type];
        }
        [Conditional("DEBUG")]
        public static void ValidatePropertyName(object instance, string propertyName)
        {
            ValidatePropertyName(instance.GetType(), propertyName);
        }
        [Conditional("DEBUG")]
        public static void ValidatePropertyName(Type type, String propertyName)
        {
            List<string> properties = RuntimeAssert.GetProperties(type);
            if (!properties.Contains(propertyName))
            {
                string message = String.Format("Property '{0}' not found in class '{1}'", propertyName, type.FullName);
                throw new PropertyNotFoundException(message);
            }
        }
    }
</code>```

And finally, PropertyNotFoundException  (it's used in above class).

```<code>public class PropertyNotFoundException : Exception
    {
        public PropertyNotFoundException(string message) : base(message)
        {

        }
    }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
INotifyPropertyChanged bug introduced by refactoring, misspelling, case-mismatch etc.

Sometimes we change the name of some of our properties, and we forget to change the "string" we pass toOnPropertyChanged() method (especially when we call this method from somewhere else), or simply misspell it, including case-mismatch.

Something like this:

public string FirstName //earlier it was simply 'Name'
{
      get { return m_name; }
      set
      {
          m_name = value ;
          OnPropertyChanged("Name"); //still 'Name'. Bug!
         //or, OnPropertyChanged("FirstNane"); //changed, but misspelled. Bug!
      }
}

Fix

protected void OnPropertyChanged(string propertyName)
{
   //this raises exception if there is something wrong (only in debug mode!).
   RuntimeAssert.ValidatePropertyName(this, propertyName);

   //your code here
}

Here is the implementation of RuntimeAssert class.

   public static class RuntimeAssert
    {
        private static Dictionary<Type, List<string>> ClassPropertyMap = new Dictionary<Type, List<string>>();
        private static List<string> GetProperties(Type type)
        {
            if (!ClassPropertyMap.ContainsKey(type))
            {
                PropertyInfo[] props = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                ClassPropertyMap.Add(type, new List<string>(props.Where(p => true).Select(p => p.Name)));
            }
            return ClassPropertyMap[type];
        }
        [Conditional("DEBUG")]
        public static void ValidatePropertyName(object instance, string propertyName)
        {
            ValidatePropertyName(instance.GetType(), propertyName);
        }
        [Conditional("DEBUG")]
        public static void ValidatePropertyName(Type type, String propertyName)
        {
            List<string> properties = RuntimeAssert.GetProperties(type);
            if (!properties.Contains(propertyName))
            {
                string message = String.Format("Property '{0}' not found in class '{1}'", propertyName, type.FullName);
                throw new PropertyNotFoundException(message);
            }
        }
    }

And finally, PropertyNotFoundException  (it's used in above class).

public class PropertyNotFoundException : Exception
    {
        public PropertyNotFoundException(string message) : base(message)
        {

        }
    }


问:
Is Java Bytecode interpreted?
The definition of interpretation (correct me if I'm wrong) is parsing code like so:

1- Translate currently parsed line to some intermediate language. 2- Run the translated line. 3- Move to the next line. 4- Translate it. 5- Run it. And so on.

If so, why do people say that the JVM interprets the Java Bytecode? What it does is execute it. The Bytecode is already translated Java source code, so there's no need to translate further.

Than why is the term interpretation involved?

If this term is used because the JVM executes the Bytecode line by line, well I'd say that any execution does that. Executes the runnable code from top to bottom. Than why use the term interpretation?

Interpretation as opposed to what?

答:
The definition of interpretation (correct me if I'm wrong) is parsing code like so:

1- Translate currently parsed line to some intermediate language. 2- Run the translated line. 3- Move to the next line. 4- Translate it. 5- Run it. And so on.

I would say your definition of "interpretation" is wrong -- there is not (necessarily) a translation step in interpretation.  So it should be:

Read a chunk of code

Execute that chunk of code

Read the next chunk of code

Execute the next chunk

...keep going

In the case of a JVM bytecode interpreter, a "chunk" is a single bytecode.  In a more traditional interpreted language, a "chunk" might be a line.  The 'execute' step might involve generating some IL for the chunk and then interpreting that IL -- in which case you have two interpreters, a high level one that invokes the lower level one.

Title: Is Java Bytecode interpreted?


答:
The easy approach is the one you describe: copy the .git hidden directory and project files to another machine where you can either commit and finish up, or just continue working.

The .git directory is where your git history is kept, so preserving this along with the actual files keeps your entire project history intact.

If you are permanently done using the original machine, I'd probably recommend this approach.

Title: Git commit not finished but can't continue on that machine

Body:
Sometimes I run into the problem of having uncommitted code on a workstation that is not ready for a commit but needs to be completed on a different workstation or laptop.

Does anyone have a solution for this problem, such as a "soft commit" or some other way of transferring the changes to another machine to work on them elsewhere?

I would prefer not to be forced to commit and push changes that are not properly implemented.


答:
The following assumes your local repo is a clone of a repo on another server, e.g. github; and that you have rights to make changes to the upstream server. In my example, I've called this upstream repo "origin". Run git remote show to list other repos, this may give you a hint as to what it's called.

I would suggest making a branch, then you can check out the branch on another machine. In fact, if you make a branch as soon as you start work, you can "commit" to your branch, have a trail and backup of your work, without having to have a stable codeset. Once you are happy with your work, you can merge it back into your "master" branch.

To branch your repo: git checkout -b MyNewBranch

To push committed changes of your new branch: git push origin MyNewBranch

To check out a branch on another machine: git checkout MyNewBranch

To switch to another branch (e.g. "master"): git checkout master

When in master, to merge MyNewBranch back in: git merge MyNewBranch

To list branches: git branch


问:
Is obtrusive JavaScript ever ok?
I was thinking that if all the users of a website are required to have JavaScript enabled, Is it ok to use obtrusive JavaScript?

I'm all for progressive enhancement, but what's the point when an advanced web application bounces users at the door if they have an old browser or JavaScript disabled?

We have a very slim target audience, and we can tell our target audience what browser and plugins/functionality they are required to have. So my question is, is mixing JS and HTML alright in that case? Like using onclick attributes.

答:
Alright, just call me the crypt keeper on all the necro I do but I have never felt the true value of this has been properly understood. Historically, it has been asserted that "unobtrusive JavaScript" or, keeping your JS out of the HTML via inline HTML event handler attributes and script tags that didn't link to a file as much as possible is a huge key element of:

Accessibility concerns

SEO

And progressive enhancement

LIES! (well, now they would be)

The truth of the matter is, you could do technically obtrusive JavaScript and still pull the above three items off. Unless you were building HTML content dynamically which was a big SEO no-no in the day.

But Stop and Think... About YOU!

Really, the big benefit, the major and most undersold win of maintaining separation has always been the direct benefit the developer gets out of it. You can have as many event handlers as you want on the same html element for the same event as is convenient. That means if a tag with class="some_class" always gets a certain behavior but also gets some bonus behavior when it's inside an id="bonus_behavior" div, we don't have to start messing with logic inside our one-allowed event handler to branch for that. We can just add or not add handlers depending on context.

Easy to Read Too

Another benefit is legibility. This was a more critical concern when browser tools consisted of IE's exclusive error message telling you that there was something wrong with [object] but IMO, it's still a big deal. CSS here, JS there and HTML is the place where both they and the server meet. With all of those things coming together in one place it makes sense to rely on the hooks (the IDs, classes, and hierarchy) to create a layer of abstraction that everything uses to connect to the HTML.

IMO, the more you CAN keep your HTML, CSS, and JS separated the easier it is to not just read but also to modify and understand what's going on. I see an empty div with "dynamic_combo_box" as a class and I have a good idea something is doing a fancy select that loads data in dynamically. I have a lead on how to find that in the JS and the CSS and if I run into the class in those concerns, I'll have a good idea what it's about and how to find it in the HTML.

Too Easy to Make Even Sloppier

And of course legibility tends to go hand in hand with maintainability. When you just do things directly by dumping it all in script tags where the relevant HTML happens to be, as often as not, it becomes easier for people to just cut and paste that script in the HTML of another page they're working on when they want similar functionality which means you now have one thing that will most likely eventually become two annoyingly similar but not 100% alike things whose behavior may become problematic over time by defying expectations and require the addition of more pointless branching to handle exceptions one needs that another didn't.

So rigging behavior to those HTML hooks encourages code re-use in a smart way. If you need to branch behavior for an alternate implementation, you just go to the same function and handle it there with HTML hierarchy or maybe a data-att triggering some alt-behavior. It's one stop-shopping for anybody wanting to understand how UI elements of a certain type work and those despicably lazy-in-a-bad-way cut & paste types will do the right/more-maintainable thing just because it's the easiest thing to do now and that's the best way to make maintainability happen. Make it the easiest "duh" thing to do even for somebody who couldn't care less whether due to panic or apathy.

But What About 2014?

It may be a legit point that in modern single-page applications, some of these stickler things maybe shouldn't be stuckled to as dogmatically as they have been but believe me when I say I don't think I'm the only one who was sold on it because it ultimately makes the work easier. I'm lazy in a (I hope) mostly-good-way. I like it when I only have to change things in one place to get changes all over an app, when I only have to look in one place to figure out what the bug is, and when I have an easy time understanding what the heck is going on and how to best re-use that code to do something very similar.

It's good like splitting out a DB or data-layer is good. It's ultimately a why-didn't-I-just-do-that time-saver like taking all of five minutes to do the laundry the night before rather than spending 10 minutes on febreezing your boxers and conducting paranoid smell checks the next morning.

For me, it is those selfish motivations that have always been the main point of why I hold on to not just unobtrusive JS but the separation of style/behavior/content concerns as much as possible even as WHAT-freaking-WG does their damnedest to muddle those concerns in understandably awesome and cool/handy ways.

Now that everybody's doing SPAs and it's almost silly trying to convince business that we should care about people who run without JS (accessibility can now be, supposedly, handled with JS-generated content), it seems like the next generation of JS devs care less about this but IMO, there is still a win there and it's mostly for you, the developer writing and maintaining this stuff. And really, that win should have always been the most underscored point but never has been for some reason because it ultimately benefits you and also the product by happy accident through virtue of being easier tweak/modify/debug.

Is it Ever Okay?

Well yeah, I guess. In a disposable throw-away app for a contest or something maybe. But I would still do it just because I'm in the habit of it and it's not actually harder to do.

Title: Is obtrusive JavaScript ever ok?


问:
Why does Rails do config in code?
According to the Pragmatic Programmers, code should be for abstractions, while configuration and details should live in metadata. Rails seems to diverge dramatically from this pattern. Much config is done in code files such as application.rb, routes.rb and the various environment.rb files, while other types of config is done in yaml files (e.g. database.yml). What is the thinking behind this design decision?

答:
Executable configs are a tradeoff between expressibility and safety/predictability.

Using a turing-complete programming language for configuration gives you many useful features "for free": Variables make let you avoid writing a same value over and over, loops avoid repeating yourself, if statements do conditionals, etc.

The disadvantage of using an executable config or a config-generator is that you can't know what the config will do without executing it. Will it execute quickly or will it get stuck in an infinite loop? What properties will it set in the end? There are also security issues it you have user-created configs - how do you sandbox the executino environment? Can they DDOS you by consuming too many resoutrces and so on...

Title: Why does Rails do config in code?


问:
Citations for inadvisability of globally unique password
I am having a disagreement with a client about the user authentication process for a system. The nub of it is that they want each user to have a globally unique password (i.e. no two users can have the same password).

I have wheeled out all the obvious arguments against this:

it's a security vulnerability,

it confuses identification with authentication,

it's pointless, etc.,

but they are insisting that there is nothing wrong with this approach.

I have done various gGoogle searches looking for authoritative (or semi-authoritative , or even just independent) opinions on this, but can't find any (mainly it's just such an obvious faux pas that it doesn't seem worth warning against, as far as I can tell).  Can anybody point me towards any such independent opinion, please?

EDIT: Thanks for all your answers, but I already understand the problems with this proposed approach/requirement, and can even explain them to the client, but the client wont't accept them, hence my request for independent and/or authoritative sources.

I'd also found the Daily WTF article, but it suffers from the problem that Jon Hopkins has pointed out - that this is such a self-evident WTF that it doesn't seem worth explaining why.

And yes, the passwords are going to be salted and hashed. In which case global uniqueness might well be difficult to ensure, but that doesn't solve my problem - it just means that I have a requirement that the client won't budge on, that's not only ill-advised, but is also difficult to implement. And if I was in a position to say "I'm not budging on salting and hashing", then I'd be in a position to say "I'm not implementing globally unique passwords".

Any pointers to independent and/or authoritative sources for why this is a bad idea still gratefully received...

答:
Enforcing unrepeatable passwords leaks information

How? Because every time a cracker attempts to create a new user with a simple password your system responds with "Nope, can't have that password", the cracker says "Goody, that's one for the list".

Leaking information about your security is generally a bad thing. OK, third parties knowing the algorithm is fine (it needs peer review) but allowing a dedicated cracker to infer keys - bad, really, really bad.

Resources describing good and bad password management policies

Read this article by security expert Bruce Schneier for an in-depth discussion of password strength.

Read this PDF by security researchers Philip Inglesant & M. Angela Sasse for an in-depth discussion of "The True Cost of Unusable Password Policies". To quote from the conclusion:

Against the world-view that “if only
  [users] understood the dangers, they
  would behave differently” [12], we
  argue that “if only security managers
  understood the true costs for users
  and the organisation, they would set
  policies differently”.

False sense of security

So the client pipes up with, "If no-one has the same password then if one is cracked then only one person is affected." No. Everyone is affected because the cracker has demonstrated that your password system is fundamentally flawed: it is vulnerable to a dictionary attack in an on-line system. It should not have been possible for a cracker to attempt multiple guesses against a password in the first place.

For on-line access 6 characters is enough

Going off-topic, but I thought it would be worth mentioning for interested readers. In security terms an on-line system is one that has an active security management process monitoring and controlling access to the data. An off-line system is one that does not (such as having encrypted data on a hard disk that has been stolen).

If you have a password system that is on-line then you don't need high security passwords. The passwords only have to be sufficiently complex to prevent guesses within 20 attempts (so a simple "name of spouse/child/pet" attack will fail). Consider the following algorithm:

Cracker guesses password using "root plus suffix" approach to minimise guesses

Credentials rejected and further login attempts prevented for N*10 seconds

If N > 20 lock account and inform administrator

N = N +1

Inform user that next login can occur at time T (calculated above)

Goto step 1

For a simple 6 character password the above algorithm will prevent dictionary attacks, whilst allowing even the most inept user on a mobile keypad to get through eventually. Nothing will prevent the so-called "rubber hose attack" where you beat the holder of the password with a rubber hose until they tell you.

For an off-line system when encrypted data is lying around on a flash drive and the cracker is at liberty to try anything against it, well you want the most resilient key you can find. But that problem is already solved.

ContentLicense: CC BY-SA 4.0


答:
I commit it. The I push it to personal branch, check out on the other side and amend. And delete the personal branch when done.

Of course you can push directly between the repos, you can use bundle or format-patch/am, but a personal branch is by far the easiest solution. And rewriting history is not a big deal as long as it's not pushed to any shared branch. In many projects people are supposed to rewind the feature branches to keep them easier to understand for review.


答:
Property/String mismatch
namely when using O/RM frameworks without linq:

```<code>    Dim crit As DetachedCriteria
    crit = DetachedCriteria.For(GetType(RemitLineItemEntity), "remit")

    If Not String.IsNullOrEmpty(LastName) Then
        If LastName.Contains("%") Then
            crit = crit.Add(New LikeExpression("LastName", LastName))
            countCrit = countCrit.Add(New LikeExpression("LastName", LastName))
        Else
            crit = crit.Add(Expression.Eq("LastName", LastName))
            countCrit = countCrit.Add(Expression.Eq("LastName", LastName))
        End If

    End If
</code>```

Then changing the LastName property on the object to SurName, or such.

Fix

Only one I know of is to use a tool to do refactoring (which most do).  They should catch the quoted field name as well, but usually use human verification on it (which leads to human error).

Title: .Net Best Practices : Common Bugs Introduced By Refactoring, Carelessness, and Newbies

Body:
What are the common bugs introduced by refactoring, carelessness, and newbies?

I would like to request the experienced programmers here to share their experience and list the bugs they used to introduce when they were inexperienced.

In your response, please write a headline mentioning the kind of bug in bold text, followed by few linebreaks, and then an explanation, cause of the bug, and finally the fix.

Body:
Property/String mismatch
namely when using O/RM frameworks without linq:

    Dim crit As DetachedCriteria
    crit = DetachedCriteria.For(GetType(RemitLineItemEntity), "remit")

    If Not String.IsNullOrEmpty(LastName) Then
        If LastName.Contains("%") Then
            crit = crit.Add(New LikeExpression("LastName", LastName))
            countCrit = countCrit.Add(New LikeExpression("LastName", LastName))
        Else
            crit = crit.Add(Expression.Eq("LastName", LastName))
            countCrit = countCrit.Add(Expression.Eq("LastName", LastName))
        End If

    End If

Then changing the LastName property on the object to SurName, or such.

Fix

Only one I know of is to use a tool to do refactoring (which most do).  They should catch the quoted field name as well, but usually use human verification on it (which leads to human error).


答:
Like others have answered, with Git you shouldn't care about non-finished code in your personal branches. However, if for some reason, you really really really don't want your unfinished work to ever touch the main repo, you can utilize Git's distributed nature!

There is a simple tool named git bundle that can help you easily pass changes around without a central repository. First, clone the repo:

```<code>git clone https://github.com/octocat/Spoon-Knife.git working_copy_1
cd working_copy_1
</code>```

make some changes and commit them to a temporary branch:

```<code>git checkout -b tmp_branch
git commit -a -m "temporary changes"
</code>```

Now, bundle them changes:

```<code>git bundle create ../tmp.bundle tmp_branch
</code>```

Now you have a bundle file you can mail to your new machine. How do you use it there? Let's create a new working copy:

```<code>cd ..
git clone https://github.com/octocat/Spoon-Knife.git working_copy_2
cd working_copy_2
</code>```

we need to treat our bundle as another remote, so we can fetch the changes from it

```<code>git remote add tmp ../tmp.bundle
git fetch tmp
</code>```

since the whole point was to transfer the changes without leaving a trace, we'll want to squash them into the working copy in order to lose the temp commit:

```<code>git merge tmp/tmp_branch --squash
</code>```

and all that is left is to remove the temporary remote:

```<code>git remote remove tmp
</code>```

VIOLA! The changes were transferred to the new working copy without leaving a trace of neither branch nor commit!

But really - this process is quite long and cumbersome. This is Git, not SVN - there really shouldn't be any reason not to push your personal branch to the central repo.

Body:
Like others have answered, with Git you shouldn't care about non-finished code in your personal branches. However, if for some reason, you really really really don't want your unfinished work to ever touch the main repo, you can utilize Git's distributed nature!

There is a simple tool named git bundle that can help you easily pass changes around without a central repository. First, clone the repo:

git clone https://github.com/octocat/Spoon-Knife.git working_copy_1
cd working_copy_1

make some changes and commit them to a temporary branch:

git checkout -b tmp_branch
git commit -a -m "temporary changes"

Now, bundle them changes:

git bundle create ../tmp.bundle tmp_branch

Now you have a bundle file you can mail to your new machine. How do you use it there? Let's create a new working copy:

cd ..
git clone https://github.com/octocat/Spoon-Knife.git working_copy_2
cd working_copy_2

we need to treat our bundle as another remote, so we can fetch the changes from it

git remote add tmp ../tmp.bundle
git fetch tmp

since the whole point was to transfer the changes without leaving a trace, we'll want to squash them into the working copy in order to lose the temp commit:

git merge tmp/tmp_branch --squash

and all that is left is to remove the temporary remote:

git remote remove tmp

VIOLA! The changes were transferred to the new working copy without leaving a trace of neither branch nor commit!

But really - this process is quite long and cumbersome. This is Git, not SVN - there really shouldn't be any reason not to push your personal branch to the central repo.


问:
Empty virtual method on base class VS abstract methods
I couldn't find a question that was not too specific to some case, so I'll try to make this very generic.

We need an extractor base class to a set of documents, for example. Each document has its specific properties, but they're ultimately documents. So we want to provide common extraction operations for all of them.

Even though they're all documents, as I said, they're somewhat different. Some may have some properties, but some may not.

Let's imagine that we have the Document base abstract class, and the FancyDocument and NotSoFancyDocument classes that inherit from it.
The FancyDocument has a SectionA, the NotSoFancyDocument doesn't.

That said, what would you defend as the best way of implementing this? Here's the two options:

Empty virtual methods on the base class

Empty virtual methods on the base class would allow the programmer to only override the methods that make sense for the different types of documents. We would then have a default behavior on the abstract base class, which would be returning the default for the methods, like this:

```<code>public abstract class Document
{
    public virtual SectionA GetDocumentSectionA()
    {
        return default(SectionA);
    }
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    // Does not implement method GetDocumentSectionA because it doesn't have a SectionA
}
</code>```

Concrete empty methods or concrete methods throwing a NotImplementedException

Since the NotSoFancyDocument does not have a SectionA, but the others do, we could either just return the default for the method in it, or we could throw a NotImplementedException. That would depend on how the program was written and some other things. We could come up with something like this:

```<code>//// Return the default value

public abstract class Document
{
    public abstract SectionA GetDocumentSectionA();
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        return default(SectionA);
    }
}
</code>```

OR

```<code>//// Throw an exception

public abstract class Document
{
    public abstract SectionA GetDocumentSectionA();
}

public class FancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        // Specific implementation
    }
}

public class NotSoFancyDocument : Document
{
    public override SectionA GetDocumentSectionA()
    {
        throw new NotImplementedException("NotSoFancyDocument does not have a section A");
    }
}
</code>```

Personally, I do think that the abstract method approach is better, since it means "Hey, I need you to be able to get a SectionA to be a document. I don't care how." while the virtual method means "Hey, I do have this SectionA here. If it's not good enough for you, feel free to change the way I get it.".

I do think the first one is a sign of object oriented programming smell.

What are your opinions on this?

答:
In this case the base class should know nothing of SectionA. The derived class should implement the extra properties that that type needs.

For certain operations where another class needs to pull information out regardless of the type of document you will want that method on the base class ideally virtual with a basic implementation and allow derived classes to override it if needed (eg ToPlainText which would just output all the sections of a document would be on Document, FancyDocument can override the implementation to also output SectionA).

For instances where another class doesn't care about the type of document but does care if it has certain properties use interfaces. IDocument would have all the common sections and Document would implement it. IDocumentWithSectionA would inheerit IDocument and FancyDocument would implement that. This then lets you derive another NeitherFancyNorNotFancyDocument that has SectionA which can also implement IDocumentsWithSectionA.

Obviously You'd have more useful names than IDocumentWithSectionA but that depends on the usecase.

TL;DR use the abstract class for what should be common to all documents and some common functionality, use interfaces as the contract saying what a document has.


问:
When an interpreter executes code: Is there a "chain of interpretations" down to the lowest level?
After doing some research and with the help of people on this site, I finally came to an understanding of what interpretation actually is.

Essentially, what interpretation means is (correct me if I'm wrong):

Scan a piece of code.

Come up with a piece of code in another language, with the same meaning.

Execute that new piece of code.

So for example, and interpreter written in Java that interprets code in C, and sees this line of code:printf("hello world");

Will come up with this line of code: System.out.println("hello world");

And will execute it (as opposed to a compiler, which will store it).

If all of this is true, then here is my question:

I think, that every execution an interpreter carries out, actually creates a chain of interpretations down to the lowest level. I'd like to know if this is true. Here is what I mean:

When an interpreter executes a line of code (which is the new line it came up with, after scanning a line), it actually tells the underlying platform to interpret it.

For example, as we know, an interpreter written in Java that interprets C code, sees printf("hello") and executes in reaction the new line of code System.out.println("hello").

But what does "executes System.out.println("hello")" actually mean? It means to tell the underlying platform (in this case the JVM) to interpret this line.

And so, another interpretation begins: The (in this example) interpreter in the JVM receives the line System.out.println(), comes up with a new line of code with the same meaning in another language, and executes it.

And when it executes the new line of code, again: It actually tells it's underlying platform to interpret it (in this example, the OS). And then another interpretation begins in the OS, which comes up with a new line of code with the same meaning in a different language, and tells an even lower level to interpret it. This continues down to the lowest level of the CPU.

My question is: Is this true? Is every execution an interpreter carries out, actually a call to the underlying platform to interpret? (Thus creating a chain of interpretations down to the lowest level?)

When people say that an interpreter executes code, do they actually mean that it tells it's underlying platform to interpret that code? (And so on?)

(Note: I might be not accurate about the function of the JVM specifically, I missed some steps there. But my question is more general, Java is just an example).

答:
Essentially, what interpretation means is (correct me if I'm wrong):

Scan a piece of code.

Come up with a piece of code in another language, with the same meaning.

Execute that new piece of code.

Again.  This is an incorrect definition.

Some interpreters behave this way.  But some don't.  For example, a typical Java bytecode interpreter (e.g. java -int) doesn't need to do any translation of the bytecodes before interpreting them.  (And if it does do some minor rewriting, it is only an optimization to make the interpreter run faster.)

When an interpreter executes a line of code (which is the new line it came up with, after scanning a line), it actually tells the underlying platform to interpret it.

No.  That is incorrect.  In fact, when an interpreter runs, it is an "execution engine" for the code that it is interpreting.  It is the execution engine itself that executes the interpreted code ... in whatever language or intermediate code or bytecode it is expressed at that point.

The underlying platform (e.g. the hardware, in the case of the bytecode interpreter in a a JVM) is executing the interpreter itself.  It is not executing the code that the interpreter is running.  The Java interpreter is not "telling" the hardware to run / interpret / execute the code. It is doing that task itself.

... as opposed to a compiler, which will store it.

The purpose of a compiler is to translate code from one form to another not to "store" it.  For example:

javac translates Java source code to bytecodes,

the JIT compiler translates bytecodes to native code, and

the C compiler gcc translates C code to native code.

Say, would the interpreter I described before, the one that will be used to run programs in a language I'll create, and is run on the JVM - Is it considered a VM?

It could be.  It depends on whether the VM is exposed to the outside world.  If it is not, then it is moot as to whether you consider it a virtual machine.

It serves as a platform for other programs to run on, which is basically what a VM is. But I don't know if it needs more specifications to be considered a VM.

There is no specification.  As I said before.  None of these terms have a specification.  They only have conventional meanings ... and no single agreed definition.

Why?  Because the meanings change over time.

Think of a dictionary.  Do the definitions in a dictionary define the word?  No.  What they actually do is to document the various common and historical meanings (plural!) of the word.  And different dictionaries may disagree, and the dictionary definitions change over time to reflect the change in language.

FOLLOWUP

I meant something like this: A code in a language has print "hi". It's interpreted in an interpreter that's written in Java. So the interpreter 'comes up' with the new line 'System.out.println("hi")` - Same meaning, different language - and executes it.

Nope.  That's not how an interpreter works.  There is no "coming up with" process.  In your example, there is no new Java code created do that.  Rather, the interpreter (which is written in Java) already includes code to execute the operation, and any other possible operation that can be expressed in the source language ... the language that is being interpreted.

(for example, and interpreter written in Java sees something like print "hi" and executes System.out.println("hi"), which will later be complied to be understood by it's underlying platform - the JVM)

Nope.  See above.  That is not how an interpreter works.

In fact what you are describing sounds like a source code to source code compiler, not an interpreter at all.

A compiler understand a line of code, and comes up with new code with the same meaning - in the language it translates to - and 'stores' it in a file.

Partly correct, but there is no requirement for the target code to be stored in a file.  For instance, the code produced by a JIT compiler is typically written to memory, ready for execution the next time the corresponding method is called.


问:
How to deal with the "programming blowhard"?
So I'm sure everyone has run into this person at one point or another, someone catches wind of your project or idea and initially shows some interest. You get to talking about some of your methods and usually around this time they interject stating how you should use method X instead, or just use library Y. But not as a friendly suggestion, but bordering on a commandment. Often repeating the same advice over and over like a overzealous parrot.

Personally, I like to reinvent the wheel when I'm learning, or even just for fun, even if it turns out worse than what's been done before. But this person apparently cannot fathom recreating ANY utility for such purposes, or possibly try something that doesn't strictly follow traditional OOP practices, and will settle for nothing except their sense of perfection, and thus naturally heave their criticism sludge down my ears full force. To top it off, they eventually start justifying their advice (retardation) by listing all the incredibly complex things they've coded single-handedly (usually along the lines of "trust me, I've made/used program X for a long time, blah blah blah").

Now, I'm far from being a programming master, I'm probably not even that good, and as such I value advice and critique, but I think advice/critique has a time and place. There is also a big difference between being helpful and being narcissistic. In the past I probably would have used a somewhat stronger George Carlin style dismissal, but I don't think burning bridges is the best approach anymore.

Do you have any advice on how to deal with this kind of verbal flogging?

答: Why do you care what this person says?  Are they your boss?  Who cares?  Every job has a guy, hopefully not you, that they avoid, or they hear him coming down the hall and they duck.  They just don't like him.  They may not even know why.  But that's just the way the world is.  Be cordial and who cares.  Sounds like you want your pound of flesh and to smack him around a little bit.</p>


问:
Why are string resources generally kept external to the code and not inside the code?
Generally, on many platforms, I'm writing my string resources to a .resx or .xml file, and then I'm getting them using some platform-dependent approach.

That is, on iOS, I'm getting them via NSBundle.MainBundle, and by using Context.Resources on Android.

What are the advantages of this approach, and why not having it directly accessible in the code, so, for example:

In a cross-platform project, any platform can access it directly, with no integration.

There are no concerns during building about whether or not the resources built well.

The coder can use functionalities such as multilanguage handling

Long story short: what is the reason why string resources are structured that way?

[Edit]

Let's say that my file is part of a "core" project shared between other project. (Think about a PCL, cross-platform project file structure.)

And suppose that my file is just totally similar to a .resx/.xml file, looking like this (I'm not a pro in xml, sorry!):

  Parameters
  Paramètres

So, this is basically a custom xml, where you point to the key/language to get the proper string.

The file would be part of the application just like you add any accessible file inside an app, and the system to access the string resources, coded using PCL. Would this add an overhead to the applications?

答:
Localization and internationalization,

Keeping the strings external allows them to change (read: translated) without needing to recompile (just a relink at most, and just dropping in a new folder at best).


答: If you have a file that contains only the string resources then you can give the resource file to a translation-agency or something like that and get a translation. I guess you can imagine how hard that could get if you would have to give a lot of codefiles to a layperson to do some translation (in addition to maybe not wanting to give out your code to whomever).</p>

Title: Why are string resources generally kept external to the code and not inside the code?

Body:
Generally, on many platforms, I'm writing my string resources to a .resx or .xml file, and then I'm getting them using some platform-dependent approach.

That is, on iOS, I'm getting them via NSBundle.MainBundle, and by using Context.Resources on Android.

What are the advantages of this approach, and why not having it directly accessible in the code, so, for example:

In a cross-platform project, any platform can access it directly, with no integration.

There are no concerns during building about whether or not the resources built well.

The coder can use functionalities such as multilanguage handling

Long story short: what is the reason why string resources are structured that way?

[Edit]

Let's say that my file is part of a "core" project shared between other project. (Think about a PCL, cross-platform project file structure.)

And suppose that my file is just totally similar to a .resx/.xml file, looking like this (I'm not a pro in xml, sorry!):

  Parameters
  Paramètres

So, this is basically a custom xml, where you point to the key/language to get the proper string.

The file would be part of the application just like you add any accessible file inside an app, and the system to access the string resources, coded using PCL. Would this add an overhead to the applications?


答:
Essentially, what interpretation means is (correct me if I'm wrong):

Scan a piece of code.

Come up with a piece of code in another language, with the same meaning.

Execute that new piece of code.

Interpreted execution is a very fuzzy term these days, but for understanding what interpretation means, this is not a good view.

At a fundamental level, a piece of code has a meaning that can be expressed as a series of real-world effects. At the lowest level, a machine instruction is a series of bytes that means, for example, "take the contents of registers A and B, treat them as numbers, add them together, and store the result in register C". Concrete electrical signals in the computer.

Executing a piece of code means performing the real-world effect. Again, at the lowest level (machine code), we call this just "execution". Hardware circuits in the CPU are triggered by the instruction's values to redirect signals so that the effect happens (e.g. they connect the adder circuit's inputs to the registers A and B, and the output to register C - this is of course a massively simplified view of things).

But when your code is in a format that the hardware doesn't directly understand (i.e. everything except machine code, even something as simple as assembly), then you need a different way of executing it. And that is where the fundamental difference between interpretation and compilation lies.

One thing you can do with code is translate it to a different form. Translation means taking code as a series of tiny bits, looking up (in a table, a switch, a series of ifs, whatever) equivalent code in the other language, and stringing the results together.

Classically, if the target language is machine code, this is called compiling.

The other thing you can do is write a program that takes a bit of the code, looks up its meaning (again, table, switch, etc.), and executes a bit of preexisting code (another little function in the program) that generates the intended real-world effect. This is the most pure form of interpreting.

However, pure interpretation in this way is not efficient. This is where things get muddled.

A pure interpreter must re-read code over and over. Unless you work in an extremely memory-sensitive environment, this is stupid. (And even if you do, it's stupid, but in a different way.) A better thing to do is do at least part of the job only one time. High-level languages are complex to understand, and I/O to read the code is costly. So there are things that you can do.

For example, you can read the code in larger chunks and build some representation of it in memory - say, an AST. That saves you from reading it over and over. But ASTs are not very memory-efficient, because they hold too much information about the exact structure of the original code.

Another thing you can do is first translate the code to a more compact form that is still a series of instructions, just simpler. Then a pure interpreter for this simpler form can execute a lot faster, because it's simpler. The CPython interpreter, for example, does this. (.pyc files are cached versions of that simpler form.)

You can also go the full compiler route and translate to machine code and let the CPU execute it, only instead of doing that once and distributing the compiled code, you do it as the program starts. This is called JIT (just in time) compilation.

You can add multiple stages to this, first translating to some simpler form, and then compiling that to machine code. And you can vary when you execute each stage. Before the program is distributed. At program startup. When the actual execution reaches a function. Etc.

Thus, you get a wide spectrum of possible execution strategies, and the simple terms "compiling" and "interpreting" become blurred. Also, there aren't compiled and interpreted languages anymore, because a single language may well have different implementations using different strategies.

But here are some examples.

C and C++ are still typically compiled to machine code ahead of time, and the compiled version is distributed. Of course, the compilers are very complex and will use intermediate formats too.

Java and C# are translated to intermediate forms (Java Bytecode and MSIL, respectively) ahead of time in a process also called compilation (because bytecode is kinda similar to machine code in structure and representation), and the compiled form is distributed. Execution of the intermediate form differs between platforms. Java implementations tend to have a pure interpreter run first, but eventually compile down often-used parts of the code to machine code. .Net, as far as I know, only compiles to machine code, at the granularity of functions (i.e. when execution calls a function for the first, time, the IL gets compiled and stored for subsequent executions).

CPython, the standard python implementation, translates to a bytecode when a file is first read (caching the result in another file), and then does pure interpretation of that bytecode.

JavaScript engines have extremely complex implementation strategies because their performance demands are so high. Mozilla's engine, for example, starts out translating to one intermediate form, and interpreting that. Then it has a JIT compiler from that form to machine code for often-used code. And for code that is used very often (and for specially annotated code), it will translate the intermediate form to a different intermediate form, and use a second JIT compiler to translate that to machine code. (The difference between the two JITs is a different trade-off between time spent compiling and quality (read: speed) of the generated code. And the second intermediate form exists because it's more suitable for the JIT that spends more time trying to optimize.)

There are hardly any pure interpreters for high-level languages anymore. In modern usage, an interpreter is a program that takes in high-level code and produces real-world effects, no matter how many translations are in-between. A compiler is a program that takes in code and produces machine code or some not-human-readable intermediate form. And a VM is a program that takes such an intermediate form and produces real-world effects. Thus you can roughly find three categories of implementations (and languages, if you go by typical implementation):

Compiled languages, where you have a compiler that produces machine code.

VM-based languages, where you have a compiler that produces intermediate code and a VM that executes it.

Interpreted languages, where you have some kind of interpreter.

Title: When an interpreter executes code: Is there a "chain of interpretations" down to the lowest level?

Body:
After doing some research and with the help of people on this site, I finally came to an understanding of what interpretation actually is.

Essentially, what interpretation means is (correct me if I'm wrong):

Scan a piece of code.

Come up with a piece of code in another language, with the same meaning.

Execute that new piece of code.

So for example, and interpreter written in Java that interprets code in C, and sees this line of code:printf("hello world");

Will come up with this line of code: System.out.println("hello world");

And will execute it (as opposed to a compiler, which will store it).

If all of this is true, then here is my question:

I think, that every execution an interpreter carries out, actually creates a chain of interpretations down to the lowest level. I'd like to know if this is true. Here is what I mean:

When an interpreter executes a line of code (which is the new line it came up with, after scanning a line), it actually tells the underlying platform to interpret it.

For example, as we know, an interpreter written in Java that interprets C code, sees printf("hello") and executes in reaction the new line of code System.out.println("hello").

But what does "executes System.out.println("hello")" actually mean? It means to tell the underlying platform (in this case the JVM) to interpret this line.

And so, another interpretation begins: The (in this example) interpreter in the JVM receives the line System.out.println(), comes up with a new line of code with the same meaning in another language, and executes it.

And when it executes the new line of code, again: It actually tells it's underlying platform to interpret it (in this example, the OS). And then another interpretation begins in the OS, which comes up with a new line of code with the same meaning in a different language, and tells an even lower level to interpret it. This continues down to the lowest level of the CPU.

My question is: Is this true? Is every execution an interpreter carries out, actually a call to the underlying platform to interpret? (Thus creating a chain of interpretations down to the lowest level?)

When people say that an interpreter executes code, do they actually mean that it tells it's underlying platform to interpret that code? (And so on?)

(Note: I might be not accurate about the function of the JVM specifically, I missed some steps there. But my question is more general, Java is just an example).


问:
In Android can we let a fragment know other fragments?
I think I have found contradictory design guidance within the Google Android documentation on fragmentation.

The first statement below advises each fragment be unaware of other fragments and always communicate only to the activity and let the activity decides what needs to be done.

Creating event callbacks to the activity

In some cases, you might need a fragment to share events with the
  activity. A good way to do that is to define a callback interface
  inside the fragment and require that the host activity implement it.
  When the activity receives a callback through the interface, it can
  share the information with other fragments in the layout as necessary.

For example, if a news application has two fragments in an
  activity—one to show a list of articles (fragment A) and another to
  display an article (fragment B)—then fragment A must tell the activity
  when a list item is selected so that it can tell fragment B to display
  the article. In this case, the OnArticleSelectedListener interface is
  declared inside fragment A:

But a second statement later on the same page, a list fragment directly instantiates detail fragment.

```<code>   if (mDualPane) {
        // We can display everything in-place with fragments, so update
        // the list to highlight the selected item and show the data.
        getListView().setItemChecked(index, true);

        // Check what fragment is currently shown, replace if needed.
        DetailsFragment details = (DetailsFragment)
                getFragmentManager().findFragmentById(R.id.details);
        if (details == null || details.getShownIndex() != index) {
            // Make new fragment to show this selection.
            details = DetailsFragment.newInstance(index);

            // Execute a transaction, replacing any existing fragment
            // with this one inside the frame.
            FragmentTransaction ft = getFragmentManager().beginTransaction();
            if (index == 0) {
                ft.replace(R.id.details, details);
            } else {
                ft.replace(R.id.a_item, details);
            }
            ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
            ft.commit();
</code>```

So my questions:

Are these contradicting each other?

Should this be left to Activity?

I feel confused, so any clarification is appreciated.

答:
Kind of yet I suppose.

The point of the first quoted paragraph should really be that they should be connected via activity, they should be connected via the parent, which may be an activity or a composite fragment. This is done to allow easier redesign where one of the fragments needs to be replaced and generally to maintain proper separation of concerns.

Now in the example they are providing some functionality to connect the fragments directly. That indeed does not look like following the above advice. It would make more sense to provide an interface through which the list widget would expose details of the selected item and an implementation of that interface using the other fragment. Then it would still be easy to just connect the two fragments via that interface from the activity, but it would at the same time provide consistent method of using different details view.


问:
Does anyone else feel Scrum isn't agile?
I am a big fan of agile development and used XP on a very successful project a few years ago. I loved everything about it, the iterative development approach, writing code around a test, pair programming, having a customer on site to run things by. It was a highly productive work environment and I never felt like I was under pressure.

However the last few places I have worked use/used Scrum. I know it's the poster child for agile development these days but I'm not 100% convinced it is agile. Below are the two main reasons why it just doesn't feel agile to me.

Project Managers Love It

Project managers, who by their very nature are obsessed with timelines, all seem to love Scrum. In my experience they seem to use the Sprint Backlog as a means to track time requirements and keep a record of how much time was spent on a given task. Instead of using a whiteboard they all use an excel sheet, which each developer is required to fill out, religiously.

In my opinion this is way too much documentation/time tracking for an agile process. Why would I waste time estimating how long a task is going to take me when I can just get on with the task itself. Or similarly why would I waste time documenting how long a task took when I can move onto the next task at hand.

Standup Meetings

The standup meetings in the previous place I worked were a nightmare. Everyday we had to explain what we had done yesterday and what what we were going to do that day. If we went over on our time "estimate" for a task the project manager would kick up a stink, and reference the Sprint Backlog as a means of showing of incompetent you are for not adhering to the timeline.

Now I understand the need for communication but surely the tone of daily meetings should be lighthearted and focus on knowledge sharing. I don't think it should turn into a where's your homework style charade. Also surely the hole point of agile is that timelines change, they shouldn't be set in stone.

Conclusion

The idea of agile is to make the software better by making the developers life easier. Therefore in my opinion any agile process used by a team should be developer led. I don't think having a project manager use a process they have labeled "agile" to track a project has anything to do with agile development.

Thoughts anyone?

答:
Yes. Even one of the "fathers" of agile doesn't agree that Scrum is really agile : youtube.com/watch?v=hG4LH6P8Syk –  Euphoric

I think this link from one of the comments above really says it all. It's worth a watch, Uncle Bob gives a brief history on Scrum and basically says Scrum is not an Agile development process because Scrum has evolved over time to become a management process. The reasons behind this appear to be because it was project managers, and not developers, who were taking the Scrum courses.


问:
How do I handle merging code that hasn't been merged in ~3 years in an agile manner?
Our team has recently adopted agile practices and most of the team is new to agile.

In our product, we use some code developed by another team and only they maintain that code. For the last 4-5 years, the previous developers have merged the code they intended to use and not all of that. Over time, the code in our branch was customized as well. Now for 3 years, these code bases have not been merged. We are expecting a lot of changes and manual conflict resolve process to perform a merge, as all of us are new to this code and also the code has been out of sync for long time.

How should we approach this kind of task/story in Agile way? Is there any guidelines to approach such unclear task where uncertainty is very high and we do not know how many conflicts/bugs will come out?

EDIT:1
please bear with me if question is not clear, let me know in comments and i will try to clarify as much as possible. So lets me try one more time.

As a AGILE team what I (and team) has learn so far is, before 2 week sprint starts, we discuss requirements with PM, understand the work needs to be done, finalize the approach for any DB design if and then two week sprint starts. in the middle one day we also do another PBR session where any new concern's can be raised for current sprint or we just continue understanding new stories for next sprint. On the last Day of Sprint we do Sprint Demo, and next Day Sprint Retrospective.

Recently I came to know word Spike. many AGILE teams use the Spike as a 2-3 days of period between sprints either at the end of sprint to finish up minor remaining task and do not need to carry the whole stories to next sprint. Or Sometimes in the beginning of sprint to finalize the design/approach or to flush out Proof of concept kind of thing.

When I (team) saw this code merge task, we are like there is no way we will be able to break down this story to confined task as 90% of things are unknown. we do not have automate test around the code, we haven't merge this code before and again this is a Baseless merge on SQL side. what ever we estimate there are highly chances that we good amount of task may remain incomplete. now in retrospective this will become bad on team. and such task can disturb team velocity as well.

So My question is How other people include such task in there AGILE team. Does this really be executed as SPRINT? or this should be one time effort by team and not logged on AGILE board? In a way i am looking for guidance on how AGILE allows to execute such task. If not Sprint is there anything else ?

答:
This is a tough one.

Having to merge two branches of code you're unfamiliar with is tough to begin with.  Add 3 years of divergent development and you've made it something I would quit my job over ;)

But let's be constructive.

There is no easy solution for merge conflicts.  You'll have to resolve these manually.

And, unfortunately, with every merge conflict comes additional risk of regression.

If you're lucky your code and the code to merge will already have very good automated test coverage.  This is important because nobody on the team knows what the intended behaviour of the innards of the application is.  Your tests will know this for you.

The idea is that, after merging both branches, your automated tests will highlight any regressions resulting from the merge.

On the other hand, you might be unlucky and find that there is very little to no test coverage.  In this case you'll have to start writing automated tests.  You can write these unit and integration tests against your code, and hopefully the other team will agree to do the same with theirs.  Otherwise,  you'll have to do it yourself.

Depending on the size of the application, achieving 100% functional coverage might not be possible in a reasonable amount of time.  The only thing I can suggest here is to focus on the most important functionality and then dedicate some time for manual regression testing to cover the rest.


问:
How do I respond to incoming network messages in a way that achieves loose coupling?
I'm working on a client-server sort of protocol right now in Ruby. I've hit a snag where I'm not entirely sure how to proceed. Currently, I have a class, Remote that signifies a remote connection (for use through EventMachine). When Remote receives a message (i.e, network packet), it sends it off to the MessageDecoder, which returns the decoded message in a hash, like so (pseudo-code ahead)

```<code>{ source = <the_remote_connection>,
  message_code = 1, // An operation code that indicates how to respond to this message
  payload = {
    packet_specific_key = packet_specific_value // provided by the decoder
  }
}
</code>```

So, when I get this back from MessageDecoder, the Remote ships it off to its ConnectionListener, which needs to decide how to distribute that message across the application. Here's the issue: Each message might require a different scope of variables. For example, one might require the instance of a World object that the ConnectionListener doesn't know about (and rightfully shouldn't - the network code should not be coupled to the rest of the program)

So my question is: how can I implement a loosely-coupled system for distributing the reception of network-ignorant messages from a remote connection in my application that somehow magically retains scopes?

EDIT: For comments, example.

Let's assume I have a World object. The World knows about the entities within it - rocks, trees, you get the general idea. So, a command comes in from the Remote saying :DestroyRock - which should invoke World#destroy_rock. The World should not know where the command to :DestroyRock comes from. It should just know that World#destroy_rock was invoked on it.

The issue is, I need some way of finding a middle-man between ConnectionListener and World#destroy_rock. ConnectionListener definitely should not be aware of the World object, because if it is, that means I've now coupled my network code to my gameplay logic.. woops. That's pretty bad.

答:
The ConnectionListener has to know about the World instance, because it needs to pass it the command. The ConnectionListener is already a middle man, adding another middle man won't solve anything. It should, however, only know it by interface. ICommandable or something. This would provide a method to pass the message to and return appropriate response, possibly an even to provide asynchronous response/message to client and possibly a filter which messages this object should handle.

Than in the initialization code you'll create the World instance and the ConnectionListener instance and register the world with the listener. Something like:

```<code>listener.addCommandable(world);
</code>```

the filter probably makes more sense here than inside the object, so perhaps

```<code>listener.addCommandable(':DestroyRock', world);
</code>```

(or with a list of commands or something).

I might also make sense to implement the interface not in the World object itself, but in an adaptor, so the World object does not need to know about the format of the command from network. Especially if there are other ways to send it commands like a stand-alone version that has both user interface and the engine in one process and does not use network.

Of course since Ruby is dynamically typed, an "interface" is just a documented set of methods.

Body:
The ConnectionListener has to know about the World instance, because it needs to pass it the command. The ConnectionListener is already a middle man, adding another middle man won't solve anything. It should, however, only know it by interface. ICommandable or something. This would provide a method to pass the message to and return appropriate response, possibly an even to provide asynchronous response/message to client and possibly a filter which messages this object should handle.

Than in the initialization code you'll create the World instance and the ConnectionListener instance and register the world with the listener. Something like:

listener.addCommandable(world);

the filter probably makes more sense here than inside the object, so perhaps

listener.addCommandable(':DestroyRock', world);

(or with a list of commands or something).

I might also make sense to implement the interface not in the World object itself, but in an adaptor, so the World object does not need to know about the format of the command from network. Especially if there are other ways to send it commands like a stand-alone version that has both user interface and the engine in one process and does not use network.

Of course since Ruby is dynamically typed, an "interface" is just a documented set of methods.


答:
I agree with MetaFight, this is a tough one.

Just to throw out a contrarian view point, do you really have to merge the code?

You have two large blocks of code that share a common ancestor.  They split off from each other at least 3 years ago.  The blocks have been maintained by two independent groups who apparently don't talk to each other.

What value does the business get from this merge effort?  You know it's going to be expensive, difficult, and take a long time.  It might be cheaper to maintain 2 code bases indefinitely than to spend dev-years merging them.  (Production-phase code maintenance is a lot cheaper than development-phase effort)

Title: How do I handle merging code that hasn't been merged in ~3 years in an agile manner?

Body:
Our team has recently adopted agile practices and most of the team is new to agile.

In our product, we use some code developed by another team and only they maintain that code. For the last 4-5 years, the previous developers have merged the code they intended to use and not all of that. Over time, the code in our branch was customized as well. Now for 3 years, these code bases have not been merged. We are expecting a lot of changes and manual conflict resolve process to perform a merge, as all of us are new to this code and also the code has been out of sync for long time.

How should we approach this kind of task/story in Agile way? Is there any guidelines to approach such unclear task where uncertainty is very high and we do not know how many conflicts/bugs will come out?

EDIT:1
please bear with me if question is not clear, let me know in comments and i will try to clarify as much as possible. So lets me try one more time.

As a AGILE team what I (and team) has learn so far is, before 2 week sprint starts, we discuss requirements with PM, understand the work needs to be done, finalize the approach for any DB design if and then two week sprint starts. in the middle one day we also do another PBR session where any new concern's can be raised for current sprint or we just continue understanding new stories for next sprint. On the last Day of Sprint we do Sprint Demo, and next Day Sprint Retrospective.

Recently I came to know word Spike. many AGILE teams use the Spike as a 2-3 days of period between sprints either at the end of sprint to finish up minor remaining task and do not need to carry the whole stories to next sprint. Or Sometimes in the beginning of sprint to finalize the design/approach or to flush out Proof of concept kind of thing.

When I (team) saw this code merge task, we are like there is no way we will be able to break down this story to confined task as 90% of things are unknown. we do not have automate test around the code, we haven't merge this code before and again this is a Baseless merge on SQL side. what ever we estimate there are highly chances that we good amount of task may remain incomplete. now in retrospective this will become bad on team. and such task can disturb team velocity as well.

So My question is How other people include such task in there AGILE team. Does this really be executed as SPRINT? or this should be one time effort by team and not logged on AGILE board? In a way i am looking for guidance on how AGILE allows to execute such task. If not Sprint is there anything else ?


问:
How to unit test hiccup template generating function?
How do I unit test a function that takes a list of maps and returns an HTML table with the same data in Clojure/Hiccup?</p>

答:
For such "small" pieces of functionality, I would just perform regression testing on examples. Write a few samples representing some cases you want to deal with, manually build the results, and compare the output.

samples could be:

empty list

list with 1 entry / 1 col

list with 4 entries

invalid data (nested map, heterogeneous keys)

This test is brittle, but the scope of the function is so small that it is hard to come up with a good definition for the service provided.

A slightly better way is to parse the html and perform specific assertions on the structure returned by the function (nbr of rows, innerText of a td etc).


问:
Not enough information in Bugs / Tickets
I work in a small team of developers that supports several pieces of software that a large multi-site company uses.

We use Spiceworks to raise issues and support requests throughout the IT department not just developers.

We constantly get tickets raised with the following or similar:

"Function X is broken, please fix it, it is urgent"

Now this statement is practically useless to me, and it wastes my time and theirs whilst I try to work out the problem often only to discover it is something they had not realised or that should be assigned to someone else.

Now my question is in what ways could I try to get people to write more information in bugs? I have thought of several ideas such as a template but I am pretty sure they would be ignored.

The only thing I can think of that would almost certainly work is to refuse to action any tickets not written correctly, but I have my doubts as to whether I would be allowed to do this.

Incidentally the people raising the bugs tend to have trouble using basic computer functions so I cant ask them to do anything very technical without a great deal of effort.

Thanks all

答:
ticket writers need to be educated how to write tickets that are helpfull to developpers.

if i receive a

```<code>"Function X is broken"
</code>```

i would reply:

```<code>what do you currently get if you execute 'X' ?

what are the steps to reproduce the broken 'X'

what exactly would you expect to happen, when "X" is executed ?
</code>```

My customers have learned, that they get faster changes/fixes if they write their tickets with these items.

it is also helpful to make compliments to a customer that follows this rule

Body:
ticket writers need to be educated how to write tickets that are helpfull to developpers.

if i receive a

"Function X is broken"

i would reply:

what do you currently get if you execute 'X' ?

what are the steps to reproduce the broken 'X'

what exactly would you expect to happen, when "X" is executed ?

My customers have learned, that they get faster changes/fixes if they write their tickets with these items.

it is also helpful to make compliments to a customer that follows this rule


答:
I'm not familiar with that piece of software but typically any bug tracking software worth its salt will require (or can be set up to require) certain fields before bugs can be submitted.

If certain users are consistently submitting poor quality reports, I'd investigate whether only certain users could submit bugs or whether some other members of staff could act as a gatekeepers.

Something you don't mention is whether any of these bugs are given a priority. Clearly if all of your bugs are coming through as high (or the same) priority, the system is being abused.

It might tempting (as others have pointed out) to simply close them as "more information required", "vague" or "unable to reproduce", but by speaking to the users to tease out more information you may learn a few things you didn't realise about how they're using the system. Even better, you might fix a showstopper early on rather than it being allowed to fester.

Title: Not enough information in Bugs / Tickets

Body:
I work in a small team of developers that supports several pieces of software that a large multi-site company uses.

We use Spiceworks to raise issues and support requests throughout the IT department not just developers.

We constantly get tickets raised with the following or similar:

"Function X is broken, please fix it, it is urgent"

Now this statement is practically useless to me, and it wastes my time and theirs whilst I try to work out the problem often only to discover it is something they had not realised or that should be assigned to someone else.

Now my question is in what ways could I try to get people to write more information in bugs? I have thought of several ideas such as a template but I am pretty sure they would be ignored.

The only thing I can think of that would almost certainly work is to refuse to action any tickets not written correctly, but I have my doubts as to whether I would be allowed to do this.

Incidentally the people raising the bugs tend to have trouble using basic computer functions so I cant ask them to do anything very technical without a great deal of effort.

Thanks all


答:
The problem with templates is that they tend to get too complex. People tend to overload those with fields that may provide information about the bug that sometimes help the debugging process and always burden the ticket sender.

Sure, it's might be useful to know what OS and browser the user used when they encountered the bug, but the majority of the bugs are "cross platform", yet the user is always forced to enter that data.

Even if those fields are optional, having too many of them will make the template look complex and cumbersome.

If you keep the template small it wouldn't get ignored. Essentially, you need to know two thinks about the bug:

What the user did

What went wrong.

And that's it! Put an additional "additional information" field for everything else the user deems important, and resist the tempt to put any other fields(unless it's contact information you can't get manually).


问:
Is Non-Deterministic Resource-Management a Leaky Abstraction?
From what I can see, there are two pervasive forms of resource-management: deterministic destruction and explicit. Examples of the former would be C++ destructors and smart pointers or Perl's DESTROY sub, whilst an example of the latter would be Ruby's blocks-to-manage-resources paradigm or .NET's IDispose interface.

Newer languages seem to opt for the latter, perhaps as a side-effect of using garbage collection systems of the non-reference-counting variety.

My question is this: given that destructors for smart pointers or reference-counting garbage collection systems -- almost being the same thing -- allow implicit and transparent resource destruction, is it a less leaky abstraction than the non-deterministic types which rely on explicit notation?

I'll give a concrete example. If you have three C++ subclasses of a single superclass, one may have an implementation that doesn't need any specific destruction. Perhaps its does its magic in another way. The fact that it doesn't need any special destruction is irrelevant -- all of the subclasses are still used in the same way.

Another example uses Ruby blocks. Two subclasses need to free resources, so the superclass opts for an interface that uses a block in the constructor, even though other specific subclasses might not need it since they require no special destruction.

Is it the case that the latter leaks implementation details of the resource destruction, whilst the former does not?

EDIT: Comparing, let's say, Ruby to Perl might be more fair since one has deterministic destruction and the other hasn't, yet they're both garbage-collected.

答:
The failure in the abstraction is actually not the fact that garbage-collection is non-deterministic, but rather in the idea that objects are "interested" in things that they hold references to, and are not interested in things to which they do not hold references.  To see why, consider the scenario of an object which maintains a counter of how often a particular control is painted.  On creation, it subscribes to the control's "paint" event, and on disposal it unsubscribes.  The click event simply increments a field, and a method getTotalClicks() returns the value of that field.

When the counter object is created, it must cause a reference to itself to be stored within the control it's monitoring.  The control really doesn't care about the counter object, and would be just as happy if the counter object, and the reference to it, ceased to exist, but as long as the reference does exist it will call that object's event handler every time it paints itself.  This action is totally useless to the control, but would be useful to anyone who would ever call getTotalClicks() on the object.

If e.g. a method were to create a new "paint-counter" object, perform some action on the control, observe how many times the control was repainted, and then abandon the paint-counter object, the object would remain subscribed to the event even though nobody would ever care if the object and all references to it simply vanished.  The objects would not become eligible for collection, however, until the control itself is.  If the method were one that would be invoked many thousands of times within the control's lifetime [a plausible scenario], it could cause a memory overflow but for the fact that the cost of N invocations would likely be O(N^2) or O(N^3) unless subscription-processing was very efficient and most operations didn't actually involve any painting.

This particular scenario could be handled by giving having the control keep a weak reference to the counter object rather than a strong one.  A weak-subscription model is helpful, but doesn't work in the general case.  Suppose that instead of wanting to have an object which monitors a single kind of event from a single control, one wanted to have an event-logger object which monitored several controls, and the system's event-handling mechanism was such that each control needed a reference to a different event-logger object.  In that case, the object linking a control to the event logger should remain alive only as long as both the control being monitored and the event logger remain useful.  If neither the control nor the event logger holds a strong reference to the linking event, it will cease to exist even though it's still "useful".  If either holds a strong event, the lifetime of the linking object may be uselessly extended even if the other one dies.

If no reference to an object exists anywhere in the universe, the object may safely be considered useless and eliminated from existence.  The fact that a reference exists to an object, however, does not imply that the object is "useful".  In many cases, the actual usefulness of objects will depend upon the existence of references to other objects which--from the GC perspective--are totally unrelated to them.

If objects are deterministically notified when nobody is interested in them, they will be able to use that information to make sure that anyone who would benefit from that knowledge is informed.  In the absence of such notification, however, there is no general way to determine what objects are considered "useful" if one knows only the set of references which exist, and not the semantic meaning attached to those references.  Thus, any model which assumes that the existence or non-existence of references is sufficient for automated resource management would be doomed even if the GC could instantly detect object abandonment.


答:
Part of my job is answering help desk tickets for my team's main application, which is used by a few thousand internal users.  While the semantics and the system are a little different, the basic principle is the same.

Always ask for more information if it's not immediately clear from the user's submission what behavior they are expecting and not receiving.  If possible, fire up the application and look at it yourself, just in case the behavior really is so obvious that "clicking on X doesn't work" was a sufficient report.  If it's internal support, a chat or telephone call may be appropriate.

Ideally, use the same phrasing used in their training or help materials to refer to the issue.  Do not be afraid to ask for error messages or screen shots, or just come out and clearly ask what they were expecting to happen and did not.

Do not be afraid to ask your users to take screen shots, reboot their computer, or provide you with files.  There is a certain level of computer expertise that it is simply inexcusable to not possess in today's world if you use a computer in your daily job, and if your employer or customer wishes to employ such people they should have in-office support who can assist them.