问:
Javascript Implementation Patterns for Server-side MVC Websites
I'm looking for information on common patterns for initializing and executing Javascript page by page in a "traditional" server-side MVC website architecture.

A few months ago, my development team began, but abandoned, a major re-architecture of our company's primary web app, including a full front-end redesign. In the process, there was some debate about the architecture of the Javascript in the current version of the site, and whether it fit into a clear, modern design pattern.

Now I've returned to the process of overhauling the front end of this and several other MVC websites (Ruby on Rails and MVC.net) to implement a responsive framework (Bootstrap), and in the process will again need to review then revamp and update a lot of Javascript.

These web applications are NOT single-page Javascript applications (in fact, we are ripping out a lot of Ajax) or designed to require a Javascript MVC pattern; these apps are basically brochure, catalog and administrative sites that follow a server-side MVC pattern. The vast majority of the Javascript required is behavioral, pre-built plugins (JQuery and Bootstrap, et al) that execute on specific DOM nodes.

I'm going to give a very brief (as brief as I can be) run-down of the current architecture only in order to illustrate the scope and type of paradigm I'm talking about. Hopefully, it will help you understand the nature of the patterns I'm looking for, but I'm not looking for commentary on the specifics of this code.

What I've done in the past is relatively straight-forward and easy to maintain, but, as mentioned above, some of the other developers don't like the current architecture.

Currently, on document ready, I execute whatever global Javascript needs to occur on every page, and then call a page-specific init function to initialize node-specific functionality, retrieving the init method from a JS object.

On each page load, something like this will happen:

```<code>$(document).ready(function(){
  $('header').menuAction();
  App.pages.executePage('home','show'); //dynamic from framework request object
});
</code>```

And the main App javascript is like

```<code>App = {
  usefulGlobalVar: 0,
  pages:
  {
    executePage: function(action, controller)
    {
       // if exists, App.pages[action][controller].init()
    },
    home:
    {
      show:
      {
         init: function()
         {
            $('#tabs').tabs(); //et. al
         },
         normalizeName: function()
         {
            // dom-specific utility function that
            // doesn't require a full-blown component/class/module
         }
      },
      edit:
          ...
    },
    user_profile:
      ...
  }
}
</code>```

Any common features and functionality requiring modularization or compotentizing is done as needed with prototyping. For common implementation of plugins, I often extend JQuery, so I can easily initialize a plugin with the same options throughout the site.

For example,

```<code>$('[data-tabs]').myTabs()
</code>```

with this code in a utility javascript file:

```<code> (function($) {
      $.fn.myTabs = function() {
        this.tabs( {
          //...common options
        });
      };
    })
</code>```

Pointers to articles, books or other discussions would be most welcome. Again, I am looking for a site-wide implementation pattern, NOT a JS MVC framework or general how-tos on creating JS classes or components.

Thanks for your help!

答:
Well, it's really hard to suggest a pattern without knowing your exact Requirements. I've personally used Revealing Module Pattern in couple of applications -- for some big international organizations, and the development team is quite happy with it. But as I said before, it really depends to your requirements.

Generally I can recommend you to take a look at Addy Osmani's JavaScript book to somehow get more familiar with what options you have.

To me both Module and Revealing Module patterns sounds like a good fit for an MVC backend.

Here is kinda similar to what I usually use:

```<code>/* main.js */
( function ( window ) {
    window.App = {
        ...
    }
})( window );

/* moduleA.js */
( function ( App ) {
    App.functionA = {
        ...
    }
})( App );

/* moduleB.js */
( function ( App ) {
    App.functionB = {
        ...
    }
})( App );
</code>```

Body:
Well, it's really hard to suggest a pattern without knowing your exact Requirements. I've personally used Revealing Module Pattern in couple of applications -- for some big international organizations, and the development team is quite happy with it. But as I said before, it really depends to your requirements.

Generally I can recommend you to take a look at Addy Osmani's JavaScript book to somehow get more familiar with what options you have.

To me both Module and Revealing Module patterns sounds like a good fit for an MVC backend.

Here is kinda similar to what I usually use:

/* main.js */
( function ( window ) {
    window.App = {
        ...
    }
})( window );

/* moduleA.js */
( function ( App ) {
    App.functionA = {
        ...
    }
})( App );

/* moduleB.js */
( function ( App ) {
    App.functionB = {
        ...
    }
})( App );


问:
How can I hide my signature in a program?
We have a university programming course and fellow students are asking some programming questions in our Facebook group. I'm a little hesitant to share all of my programs, especially if it's something cool for one of the assignments, since these are looked at by the TAs and they might notice if somebody has the same program and start asking questions on where it came from. Still, sometimes I'd like to share my code to help others, but I don't wanting people just grabbing my work.(Clarification: We are allowed to collaborate with the tasks) This is of course a thin line. While I want to help some people, I'm concerned that they may not have the academic honesty to rewrite the code on their own.

Most of my fellow students are not very advanced in their skills, so I'd get away with say hiding my name in Base-64 encoded string crafted into a discrete place. Still, it may be too obvious for a random string to be sitting around.

What options exist to hide my name in a program without it looking suspicious?

I've seen over at CodeGolf that they have made ascii art turn into other things when evaluated. Are there similar strategies I could utilize? The ideal solution would be something that looks like something that fits in discreetly but in reality has a function to prove that I coded it from the beginning.

Clarification: (Sorry, should have said this earlier) We're allowed to collaborate but have to explain our programs to the TAs to get the points. It's just for satisfaction to hide some Easter Eggs in other's code if it leaks out, especially since it may be tempting to exchange programs to check that the answers to problems they generate are equivalent etc or to see how others solve the problem.

答:
Use your signature not in your code, but in a publicly accessible development log.

Publish your code at a public Github repo. Include a Docblock with your name in the "Author" field. This way there's a public record of you being the actual author of the program.

This may not qualify as "hiding", but in my opinion, it does. If a student decides to copy your code, they will think that they only have to swap their signature for yours. Imagine their surprise when you present public evidence of their wrongdoing. To make matters worse for them, it's accessible online. You can even use an online tool, such as Diffchecker, to demonstrate which parts of your code were stolen!

EDIT: As pointed out in the comments, make sure your school allows to share your work this way! OP indicated that their institution is OK with this, but yours might not be!

ContentLicense: CC BY-SA 3.0


答:
Like the above answer I encourage using something like Github to log your development of the code, there are other methods that you could use to cover your back such as emailing the source to yourself prior to the sharing of it, though a publicly viewable repository is what I'd strongly suggest.

That is of course if the sharing of code is highly necessary. What about pseudo-code? or like "ratchet freak" stated, share the idea not the implementation. (this makes more sense for more complex code)

Title: How can I hide my signature in a program?

Body:
We have a university programming course and fellow students are asking some programming questions in our Facebook group. I'm a little hesitant to share all of my programs, especially if it's something cool for one of the assignments, since these are looked at by the TAs and they might notice if somebody has the same program and start asking questions on where it came from. Still, sometimes I'd like to share my code to help others, but I don't wanting people just grabbing my work.(Clarification: We are allowed to collaborate with the tasks) This is of course a thin line. While I want to help some people, I'm concerned that they may not have the academic honesty to rewrite the code on their own.

Most of my fellow students are not very advanced in their skills, so I'd get away with say hiding my name in Base-64 encoded string crafted into a discrete place. Still, it may be too obvious for a random string to be sitting around.

What options exist to hide my name in a program without it looking suspicious?

I've seen over at CodeGolf that they have made ascii art turn into other things when evaluated. Are there similar strategies I could utilize? The ideal solution would be something that looks like something that fits in discreetly but in reality has a function to prove that I coded it from the beginning.

Clarification: (Sorry, should have said this earlier) We're allowed to collaborate but have to explain our programs to the TAs to get the points. It's just for satisfaction to hide some Easter Eggs in other's code if it leaks out, especially since it may be tempting to exchange programs to check that the answers to problems they generate are equivalent etc or to see how others solve the problem.


问:
Is it safe to generate client nonces using random number generator?
I am making HTTP calls on the client side and the server expects me to supply a client nonce. It needs to be 4 bytes long. I am planning to use this combination:

```<code>base64(parts of the MAC address + random bits generated by RNG)
</code>```

Given that the protocol is created by experts (thus its security is not to be questioned), is my nonce calculation acceptable in your view ?

答:
From a cryptographic protocol perspective what is usually important about a nonce (number used once) is its one-timeness. Having it generated with a (P)RNG is rather a matter of convenience. If a cryptographic protocol has specific entropy requirements on a nonce or assumes it to be otherwise cryptographically secure in some way - that would be typically known, communicated or stated upfront, because that isn't a standard expectation.

I am making HTTP calls on the client side and the server expects me to supply a client nonce

This is a typical scenario for the prevention of a replay attack - relying on the one-timeness of certain parts of the client input.

I am planning to use this combination:
      base64(parts of the MAC address + random bits generated by RNG)

When you rely on parts of the MAC address as an input to a linear transformation, you are setting yourself for an increased probability of the nonce repeating, increasing the chance of a successful replay attack, or alternatively you increase the chance of an adversary guessing your next nonce in advance, making her job easier in a sense.

Notwithstanding, in an expert chosen cryptographic protocol (as assumed in the question) it will be more common for both parties to choose a nonce, mitigating inadequate choice of a nonce by only one party. With a server nonce and a client nonce, establishing a communication frequently looks like this,

server -> client: [snonce, challenge]

client ->server:  [cnonce, f(cnonce, snonce, challenge)]

and when you don't chose cnonce adequately, or don't have a client nonce at all, an adversary can observe f(snonce, challenge) responses, where all the inputs are chosen by it, when it masquerades as a server. This can at times deteriorate to a chosen plaintext attack.

I suggest that you simplify the nonce to be along the lines of,

```<code>cnonce = base64(random bits generated by RNG)
</code>```

where you RNG has sufficient entropy. And if you need repeatability for test purposes, eg if you run your protocol client side tests in a farm on different boxes you can:

```<code>seed(RNG, parts of the MAC address)
cnonce = base64(random bits generated by RNG)
</code>```

That way your tests on every box will be amenable for debugging.

Body:
From a cryptographic protocol perspective what is usually important about a nonce (number used once) is its one-timeness. Having it generated with a (P)RNG is rather a matter of convenience. If a cryptographic protocol has specific entropy requirements on a nonce or assumes it to be otherwise cryptographically secure in some way - that would be typically known, communicated or stated upfront, because that isn't a standard expectation.

I am making HTTP calls on the client side and the server expects me to supply a client nonce

This is a typical scenario for the prevention of a replay attack - relying on the one-timeness of certain parts of the client input.

I am planning to use this combination:
      base64(parts of the MAC address + random bits generated by RNG)

When you rely on parts of the MAC address as an input to a linear transformation, you are setting yourself for an increased probability of the nonce repeating, increasing the chance of a successful replay attack, or alternatively you increase the chance of an adversary guessing your next nonce in advance, making her job easier in a sense.

Notwithstanding, in an expert chosen cryptographic protocol (as assumed in the question) it will be more common for both parties to choose a nonce, mitigating inadequate choice of a nonce by only one party. With a server nonce and a client nonce, establishing a communication frequently looks like this,

server -> client: [snonce, challenge]

client ->server:  [cnonce, f(cnonce, snonce, challenge)]

and when you don't chose cnonce adequately, or don't have a client nonce at all, an adversary can observe f(snonce, challenge) responses, where all the inputs are chosen by it, when it masquerades as a server. This can at times deteriorate to a chosen plaintext attack.

I suggest that you simplify the nonce to be along the lines of,

cnonce = base64(random bits generated by RNG)

where you RNG has sufficient entropy. And if you need repeatability for test purposes, eg if you run your protocol client side tests in a farm on different boxes you can:

seed(RNG, parts of the MAC address)
cnonce = base64(random bits generated by RNG)

That way your tests on every box will be amenable for debugging.


问:
Mongo Licensing (AGPLv3)
I'm going to include MongoDb(AGPLv3) in my product. My product is SaaS, I don't install this to client directly. My software is ASP.NET MVC website. But MongoDb's drivers for .Net is under Apache
My questions are:

1) Should I license my software under AGPLv3 license if I use Mongo? I use them across drivers which written on Apache, but somewhere I've heard that if use GPL component in your software you must license whole your product under GPL

2) If I license my website under AGPLv3 should I provide code for all customers?

Thank you for answers?

答:
If your product enhances the MongoDb database server in any way, then you must release your software under AGPL (or you must get a commercial license).

If your product just uses the MongoDb to store data in, then only the license terms for the MongoDB drivers are relevant and you can chose any license that is compatible with the Apache 2.0 license (which is just about any possible license).

If you choose to license your software under AGPLv3, then you are required to make the sources available to anyone that can use your services.

Title: Mongo Licensing (AGPLv3)


问:
heading in right direction? C++ and class templates
I'm working on some inherited code in C++ and am trying to use 2 classes with templates as I need 2-types of each class to operate on floating point or integer data (double v uint64_t to be exact).

In the two classes that I'm trying to "templatize"(?), one inherits from the other.  Data definitions needed for both are defined in the 'more base' class, some with the parameterized typename 'T', and some with resolved types (e.g. 'int') in the 'protected:' section.

The corresponding implementation (.cc) file for the more base class compiles 'ok', but the implementation file for the derived class (which is also 'templated') isn't seeing the the class data from the 1st template.

I thinking that the derived class file wants to see a resolved version
of the more base class's template definition, but am not sure.

Example:
more base class template file (.h) has:

```<code>template < typename T > class FieldMeter : public Meter {
...
protected:
    int numfields_;
    F *fields_;
    F total_, used_, lastused_;
...
};
</code>```

'less base' class (.h) file:

```<code>template <typename T> class FieldMeterGraph : public FieldMeter <T> {
    ...
}
</code>```

Problem comes in less-base class .cc file when accessing 'numfields_'
or 'fields_':

```<code>fieldmetergraph.cc:51:24: error: ‘numfields_’ was not declared in this scope
  if (!heightfield_  && numfields_>0 && graphNumCols_ >0)
</code>```

When both were simple classes, I didn't get the above, so it's a case
where data being declared in the more base, 'templatized' class isn't accessible in the implementation of a derived template.

My terminology may be a bit off -- but it seems like this should be
doable -- with "end classes" like "cpumeter" that would pass a
solid data type (uint64_t) to the toplevel FieldMeterGraph template.

I'm tempted to resort to storing the type at compile time, and doing
the resolution manually, at run-time like I would in 'C', but as I
understand it, this should be resolvable by the compiler (g++ using
C++11), at compile time.

I do have Stroustrup's 4th tomb as reference, but it seems his examples
are tending toward being a bit too generic for me to correctly derive
a resolvable, concrete example that g++ likes (though g++'s error messages do seem to be extraordinarily more helpful and precise compared to what I normally get in perl..)....

If someone knows how to more quickly resolve my conundrum, than my randomly trying various things that don't work, it would be appreciated!  ;-)

Thanks!

答:
The C++ standard does not require to lookup non-dependent names (ie, non-dependent on the template-parameter) in dependent bases, so there is no "better" solution, apart from relying on non-standard behaviour of certain compilers.

The suggestion that you've got from @Sjoerd in the comments is appropriate, as this is an implicitly dependent name. Generally, you can use one of the following forms:

this->member_;

FieldMeter<T>::member_;

Note that while the above is identical in effect for a field, you have to carefully make the distinction when you are dealing with virtual methods, for example, FieldMeter<T>::get_member_() vs. this->get_member_(), as the former will not do a virtual dispatch.


答:
"since these are looked at by the TAs and they might notice if somebody has the same program"

I'd hope so, it's part their job to detect and punish cheating, plagiarism, and other fraud.

And duplicating the work of others and passing it off as your own is that, cheating and plagiarism.

So quite simple: don't give out your work to others. Help them write their own if you want by giving them ideas on how to solve problems, then let them do their own coding.


问:
Does "write quality code" advice apply to companies of any scale?
I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower.

Books like The Mythical Man Month by Fred Brooks or Rapid Development by Steve McConnell confirmed my thoughts. Professional experience in medium-scale companies also showed me how much money and time is wasted by not even trying to do quality work.

At the same time, I often heard my colleagues complaining that constantly maintaining good code quality or simply achieving good code quality at all is too complicated for small scale companies and small teams:

It's just too expensive to get the people able to write and maintain quality code.

If the company can hire either two persons for $3 000 per month or one person for $6 000 per month, most managers would consider that two persons will be more productive than one: maybe not by a factor of two, but still. Or the small company can hire one person for $3 000 per month and spend the remaining 3 000 for something else.

There are too many aspects to take in account in order to be able to do it within a small team.

A single person can hardly take care of the style of code, readability, architecture, design, ease of testing, testing itself, reliability, security, ease of use, performance, etc.

And it doesn't worth it.

It's not like a piece of code will remain in the code base for the next fifteen years and will be read thousands of times by hundreds of developers. Chances are, the same person will maintain this piece of software for the next five years, then just throw it away and write a better one from scratch.

I usually reply that one should remember the productivity factor of 1:10 among developers and that most of the time is spent not writing code, but maintaining it. This means that low quality code is still ways more expensive.

But is it so?

Should every company, no matter its scale, try to hire the best possible developers they can afford, and encourage them to write quality code, or there is scale above which code quality becomes just a burden, a waste of time and money?

答:
I think they should try and get the best, but what is best in some situations doesn't apply to others. It depends on the management of the company/development team, but companies of different sizes can typically have these issues for different reasons. In the book, "Dreaming in Code", their project had talent, time, money and a desire to create something great, but they may have been better off with one pretty-good programmer instead of the pack of 10x developers that managed to create a big mess that took forever.

Prototype - If you would get the requirements from the business side of a startup, it would probably sound more like a prototype, but try to convince a developer of that when you release it into the wild. That doesn't mean it won't benefit from a 10x programmer. I think one of the biggest factors in that "10:1" development ratio, is the ability to build things lesser programmers just can't do (1000:1 ?). Many large companies have startup like projects and can suffer the same fate.

Good Enough to Say "No" Good programmers are in a better position to refuse to write bad code. They've experienced the negative consequences first hand and are better at persuading the powers that be, but I don't care how good you are, if the business pushes enough, you'll write crap. Arbitrary deadlines are why there is enough time to do it over instead of doing it "correctly" the first time. Larger companies have plenty of managers who have nothing better to do than to keep asking when things are going to be finished.

Best Practice Habits Good programmers develop fluency and good habits because they study, take the time to learn, but most of all believe in them. They don't waste time pissing and moaning about: tests, documentation, source control, bug tracking, code reviews and standards. They know how this makes your job easier. They may not know a lot of languages, but that's not because they refuse to use them. There's a difference. Thousands of developers are able to be productive with Git, what makes you so special? Large companies can hire developers of many levels and should be creating an apprentice program, but just because you write 10x code doesn't mean you have the ability to leverage your talent and teach others.

Hiring

Attracting Talent - Many positions are just unattractive to good programmers. Part of it is salary, but also consider the rest of this list. Some like stable companies, others want a startup. Tech companies are usually more attractive than those in other sectors.

Ability to recognize talent. Good programmers want to work with other good programmers or at least potentially good programmers. A company may make one lucky find, but rarely can they build a complete team. Larger companies will build HR staffs that are good at hiring core talent (non-technical), but have no insight to hiring programmers. They sometimes rely on recruiters.

Keeping Talent - Why hire top developers if they have no control? Who is making these so called better decisions? Creative people struggle on the assembly line. Don't lie and tell them a new feature is needed immediately to close the next sale when in fact, it's just a nice to have. Talent will eventually leave. Non-technical/creative companies struggle because they try to make the programmers work like everyone else.

Recognizing Good Code - Most of the code written is never been seen by anyone else who writes code. Clients want results. Sometimes you can convince them a new feature is going to be difficult because of the drastic change in requirements, when in fact, the code is poorly designed.

Most companies will settle for lesser talent because they just have all this other baggage that is required instead of the skills needed to do the job. "We don't want someone who just sits in the corner and writes code." A lot of developers don't shine on the "Tell me about yourself." question, but just love to talk about the things they build. I saw a guy sit very quietly at a dinner party, but when he started showing the host how to stretch the screen size to use up all the space on the monitor, I thought he was in sales. He was even able to do it in a black t-shirt - The Horror.


答:
The code quality is not about if it worths or not, it's a way of doing things. The quality code always worth it.

If a company don't care about it, this give you a key indicator that it's not a good software development company, it's simply one more software company. Good companies try to refactor every piece of code that is not very mantainable or architectured.

You'll never write the perfect code, but as we do in every aspect of our lifes, you need recheck it, refactor it and use some tools to help you following best practices.

Title: Does "write quality code" advice apply to companies of any scale?

Body:
I carefully followed the "always write quality code, unless you're writing a prototype" advice during my career as freelancer and software developer. I was convinced pretty early that avoiding to do code reviews, testing, QA or refactoring doesn't make the project faster, but only slower.

Books like The Mythical Man Month by Fred Brooks or Rapid Development by Steve McConnell confirmed my thoughts. Professional experience in medium-scale companies also showed me how much money and time is wasted by not even trying to do quality work.

At the same time, I often heard my colleagues complaining that constantly maintaining good code quality or simply achieving good code quality at all is too complicated for small scale companies and small teams:

It's just too expensive to get the people able to write and maintain quality code.

If the company can hire either two persons for $3 000 per month or one person for $6 000 per month, most managers would consider that two persons will be more productive than one: maybe not by a factor of two, but still. Or the small company can hire one person for $3 000 per month and spend the remaining 3 000 for something else.

There are too many aspects to take in account in order to be able to do it within a small team.

A single person can hardly take care of the style of code, readability, architecture, design, ease of testing, testing itself, reliability, security, ease of use, performance, etc.

And it doesn't worth it.

It's not like a piece of code will remain in the code base for the next fifteen years and will be read thousands of times by hundreds of developers. Chances are, the same person will maintain this piece of software for the next five years, then just throw it away and write a better one from scratch.

I usually reply that one should remember the productivity factor of 1:10 among developers and that most of the time is spent not writing code, but maintaining it. This means that low quality code is still ways more expensive.

But is it so?

Should every company, no matter its scale, try to hire the best possible developers they can afford, and encourage them to write quality code, or there is scale above which code quality becomes just a burden, a waste of time and money?


问:
Implementing a basic interpreter - should I learn regular expressions?
For fun and for practice, I'm thinking of maybe implementing a very basic programming language to run on a simple interpreter written in Java.

My question is this:

Is it a 'must' to know regular expressions when designing an interpreter, for parsing the text? Should I learn this topic before starting to implement the interpreter?

Or is it enough to just run through the text, break down into strings, etc, i.e. do 'basic parsing' without regular expressions?

答:
I believe you should not use Regular Expressions until you get to the point -- in your lexer or parser, where you can only deal with Type-3 of Chomsky hierarchy.

As @Sk-logic mentioned in the comments, parsing a non-regular language with regular expressions wouldn't work, simply because of the lack of recursive-ness in regular expressions -- in my opinion.

Parsing something like CSS Selectors could be a good fit for regular expressions, however working on anything above the Type-3 would get you in trouble at some point, I'd say.


问:
Planning troubleshooting in a sprint
From time to time we face difficult problems which are hard to reproduce. Creating a planning for solving such an issue is (nearly) undoable.

What we do at the moment is break these up in analyses/reproduction and solving the problem. As long as know nothing we plan a number of hours to investigate and book off these hours by effort and not by result.

This does not feel like a true agile sprint. Do you guys have any suggestion how to improve this situation?

答:
In agile, there is the term Spike where you spend time (usually fixed in my experience) investigating an issue in order to be able to make an estimate for a story. In your case, if you are doing Scrum and trying to get estimates for the tasks on a bug, you might need to run a Spike (as you are doing) so that you can estimate the work remaining.

These Spikes can also be used for prioritization. If the Spike discovers that the issue is unlikely to occur, or only occurs in very specific hardware scenarios, or only on the second Tuesday of a month ending in 'Y', you may decide to lower the priority in the backlog for this bug.

That being said, for bugs I wouldn't usually do this. I tend to just grab 'x' bugs into the sprint and have the team work on them in priority order alongside the normal group of stories that are being worked on. If during that work we discover information that might affect priority, then we act on it then.

Title: Planning troubleshooting in a sprint


问:
Does OOP fulfill the promise of code reuse? What alternatives are there to achieve code reuse?
Perhaps the greatest promise of using object-oriented paradigm is the code reuse. Some dispute that this was achieved. Why was it (not) achieved?

Does code reuse as OOP defines it, make projects more productive?

Or more manageable? Or easier to maintain? Or with more quality?

Probably we all agree that code reuse is a good thing, but there are several ways to achieve this goal. The question is about the method of code reuse offered by OOP. Was it a good thing? Are there better methods to achieved code reuse than object orientation, sub-classing, polymorphism, etc.? What ways are better? Why?

Tell us your experience with OOP reuse or other paradigms reuse.

答: In my experience, I've had more success leveraging "reusable" code through generic programming facilities (like C++ templates) than I've had using OOP principles like inheritance hierarchies.</p>

ContentLicense: CC BY-SA 2.5


问:
Object Identity and Mutability
I was reading a proposal for value types in Java, and I came across this sentence: "Object identity serves only to support mutability, where an object’s state can be mutated but remains the same intrinsic object."

From what I understand (albeit tentatively), object identity is the idea of your variable acting as a pointer or reference to an object located elsewhere in memory (such as objects instantiated on the heap in Java or C#). So what would this have to do with object mutability? Does this imply that, for example, instantiated objects on the stack in C++ are immutable? I'm having trouble seeing the link here.

答:
Before tackling identity, let's define what we mean by equality a little more precisely. We say two things are equal if and only if we can't tell them apart (see: Identity of indiscernibles). That means that whether two things are equal or not depends on the means we have to inspect them.

Let's think about that some more in programming terms. Let's leave our preconceptions at the door and suppose we're working in a brand-new unknown language where all variables and values are immutable. By the definition above, two values A and B are equal if and only if there are NO programs in the language that yield different results when A is used in place of B or vice-versa. Let's say A and B are (IEEE 754) floats, and when substituted into the expression _ + 1.0, the result is 1.0 for both A and B. Surely A and B are both zero. Are they equal? That depends - does the language provide any function that allows me to determine the sign of the zero? If it doesn't, they're equal; if it does, they may not be.

So two values are equal any time they give the same results for all possible combinations of operations they support. Immutable values in particular don't produce different results depending on which operations were previously applied to them. For that reason, we don't care if two variables point to two copies of the same value or if they both point to the same copy.

What does this have to do with mutability? Mutability implies our language has some notion of a memory cell whose contents can be overwritten. Let's say we add support for mutable memory cells to our language:

ref <value> creates a new memory cell, distinct from all others, initialized to <value>.

<variable> := <value> overwrites the contents of a reference cell.

!<variable> returns the value currently stored in a reference cell.

Now let's think about what equality means for memory cells. Suppose A = ref 0 and B = A. Consider this program:

```<code>A := 1
print(!_)
</code>```

Substituting the blank for A prints 1, and substituting for B prints 1 as well. Now suppose A = ref 0 and B = ref 0. In this case, substituting into the above program prints 1 and 0, since now A and B point to distinct memory cells.

So it does matter to us whether two references point to the same memory cell or different memory cells. Since that matters, it'd be useful to have an efficient and general way of telling two references apart. Our current method of comparing the values they hold, and if they're equal mutating one of them is troublesome for a number of reasons:

It depends on being able to compare the values stored in the memory cells for equality. Equality doesn't make sense for all types - for example, it's generally meaningless for functions, because there's no general method to determine if two unknown functions are equal (this is venturing into Halting Problem territory). So given two references to memory cells storing functions, we can't compare the functions they hold for equality.

It depends on having some value that we can assign to one of the two references. So even if equality made sense for all types in the language, we still need access to a value for each type we want to compare. What if constructing a value of that type has side effects?

The reference value we use to mutate one of the references must be different from the value the memory cell already has, so we actually need two values.

The code to compare references of different types will look exactly the same save for the two values we use.

We need to back up and restore the value of the reference we mutate to avoid changing the meaning of the program.

So it'd be useful for the language to provide an operation to directly check if two references point to the same mutable memory cell. Such a function is pointless for immutable values; in fact, I'd say it's downright harmful. If there existed a way to tell if two 1s are stored in different places in memory, then there can be programs that care whether I pass one 1 or the other. I really don't want to worry about whether I have "the right 1"; math is hard enough as it is! So it's clear that being able to check for memory equality is mainly useful for mutable types.

Title: Object Identity and Mutability

Body:
Before tackling identity, let's define what we mean by equality a little more precisely. We say two things are equal if and only if we can't tell them apart (see: Identity of indiscernibles). That means that whether two things are equal or not depends on the means we have to inspect them.

Let's think about that some more in programming terms. Let's leave our preconceptions at the door and suppose we're working in a brand-new unknown language where all variables and values are immutable. By the definition above, two values A and B are equal if and only if there are NO programs in the language that yield different results when A is used in place of B or vice-versa. Let's say A and B are (IEEE 754) floats, and when substituted into the expression _ + 1.0, the result is 1.0 for both A and B. Surely A and B are both zero. Are they equal? That depends - does the language provide any function that allows me to determine the sign of the zero? If it doesn't, they're equal; if it does, they may not be.

So two values are equal any time they give the same results for all possible combinations of operations they support. Immutable values in particular don't produce different results depending on which operations were previously applied to them. For that reason, we don't care if two variables point to two copies of the same value or if they both point to the same copy.

What does this have to do with mutability? Mutability implies our language has some notion of a memory cell whose contents can be overwritten. Let's say we add support for mutable memory cells to our language:

ref <value> creates a new memory cell, distinct from all others, initialized to <value>.

<variable> := <value> overwrites the contents of a reference cell.

!<variable> returns the value currently stored in a reference cell.

Now let's think about what equality means for memory cells. Suppose A = ref 0 and B = A. Consider this program:

A := 1
print(!_)

Substituting the blank for A prints 1, and substituting for B prints 1 as well. Now suppose A = ref 0 and B = ref 0. In this case, substituting into the above program prints 1 and 0, since now A and B point to distinct memory cells.

So it does matter to us whether two references point to the same memory cell or different memory cells. Since that matters, it'd be useful to have an efficient and general way of telling two references apart. Our current method of comparing the values they hold, and if they're equal mutating one of them is troublesome for a number of reasons:

It depends on being able to compare the values stored in the memory cells for equality. Equality doesn't make sense for all types - for example, it's generally meaningless for functions, because there's no general method to determine if two unknown functions are equal (this is venturing into Halting Problem territory). So given two references to memory cells storing functions, we can't compare the functions they hold for equality.

It depends on having some value that we can assign to one of the two references. So even if equality made sense for all types in the language, we still need access to a value for each type we want to compare. What if constructing a value of that type has side effects?

The reference value we use to mutate one of the references must be different from the value the memory cell already has, so we actually need two values.

The code to compare references of different types will look exactly the same save for the two values we use.

We need to back up and restore the value of the reference we mutate to avoid changing the meaning of the program.

So it'd be useful for the language to provide an operation to directly check if two references point to the same mutable memory cell. Such a function is pointless for immutable values; in fact, I'd say it's downright harmful. If there existed a way to tell if two 1s are stored in different places in memory, then there can be programs that care whether I pass one 1 or the other. I really don't want to worry about whether I have "the right 1"; math is hard enough as it is! So it's clear that being able to check for memory equality is mainly useful for mutable types.


答:
I think ITIL has a nice take on the subject by distinguishing between problems and incidents. You can not fix an incident ... somebody has to investigate and figure out the problem behind that incident.
That way to look at things has a certain overhead, but it can help in many different ways as the scope of a project increases.

That is pretty much what you are doing, I guess. I have not read the linked question that gnat posted, but I think that an incident does not belong in a Sprint. It needs to reach problem status first - which means the cause has to be known and a solution for the problem must have been proposed.

In some cases the Impediment Backlog might be the right place, though ... if impediments are to blame (not a lack of clarity) which the product owner (? I think ?) can tackle (or have somebody tackle).

Title: Planning troubleshooting in a sprint

Body:
From time to time we face difficult problems which are hard to reproduce. Creating a planning for solving such an issue is (nearly) undoable.

What we do at the moment is break these up in analyses/reproduction and solving the problem. As long as know nothing we plan a number of hours to investigate and book off these hours by effort and not by result.

This does not feel like a true agile sprint. Do you guys have any suggestion how to improve this situation?


答:
I think that GitHub or a similar solution is okay, BUT there are two things to consider:

This is still giving your work to others who are supposed to do it by themselves, so it might be punishable no matter if you hide some sort of an Easter egg in it or not.

The policy of the school might actually be pretty restrictive to such things. In Germany, for example, there are a number of universities, who even make their students sign a sort of a "contract", which states that everything they develop as a part of an assignment given in this and that course is property of the university and cannot be distributed in any form without the explicit permission of the institution. So before posting school stuff on the Internet I strongly advice you to ask (there are usually people who work on these things in each and every educational and scientific institution), because you might actually get into trouble and with that I don't mean just getting an F, but much worse. If you really want to help your mates, you can ask your professor if you can be a tutor or something similar and do it all out in the open.


问:
How can I re-use object from another project?
I have a first project has a feature to viewing, inserting and updating an employee record, with this possibly I will create a java class for the UI and another for the database connection with commands for viewing, inserting and updating a record.

Then I have a second project that will compute the salary of employee. How can I re-use object from the first project?

Should I get the Java or the class file or both of the first project and saved it to the project folder of the second project? How can add a feature of object from the first class?

答:
There're several ways to do that:

Copy the .java file into your project files. This has the disadvantage that you will have two source files.

Add the path to the .class file to your project's classpath.

Create a .jar file and add the path to the .jar file to your project's classpath. Note that the path includes the jar file itself, as if it were a folder. This make it cleaner when you want to share more than just one class, and it's the standard way of distributing libraries.

If you are using Eclipse, you can tell eclipse to add OldProject to NewProject's built path. Then you can import OldProject classes in your classes with the import reserverd word. Also when creating NewProject's jar for distribution, Eclipse will offer you the option of including OldProject classes in the bundle.


问:
Where should you put functions and variables that are only needed by one function in a class?
Say you have a Car class. Properties that make sense for a Car class might be:

```<code>var make;
var model;
var year;
var turnOn; // a function
</code>```

But the turnOn function is very complicated and ends up needing a static variable and a couple sub functions:

```<code>var isTurningOn; // too specific to be a class variable
function turnOn() {
    // 30 lines to start the engine
    // 30 lines to start the air conditioner
    // 30 lines to start the radio
}
</code>```

So now we have a function that maybe isn't really suitable to be made into its own class and it's polluting the Car class with a variable that only the turnOn function ever uses. Plus the function contains sections of code that should be made into their own functions. So what do you do in situations like this?

答:
Most of the existing answers sound like they're heading toward Needless Complexity.

I agree that the turnOn function doesn't need to be in its own class, however isTurningOn makes sense as an instance member variable, because it tracks part of the state of each Car instance. Split turnOn into shorter, more specific private methods and leave it at that for now.

Keep things simple until you find that adding complexity simplifies something else. If your Car is just as you describe it: a couple of member variables, a state variable, and a turnOn function, there's absolutely no reason to split it into multiple classes. It's just not that complex yet.


问:
Python shelve class rename
The main reason I use Shelve is to be able to quickly develop code without worrying about db table structure. Unfortunately changing a class name from, say, 'class1' to 'class2' gives "AttributeError: 'module' object has no attribute 'class2'" on the next run. What is the canonical way to rename a Shelved class? What other similar surprises are lurking deeper into the Shelve db structure?</p>

答:
Shelve uses pickle to serialize objects. Pickle loads objects by name; the module and class name are stored and looked up when deserialising.

The easiest way to support 'legacy' names is to simply create an alias:

```<code>class NewName(object):
    # a renamed object, once named OldName

# backwards-compatible names for unpickling
OldName = NewName
</code>```

When unpickling, modulename.OldName is looked up and used, which is simply the same class as NewName. When storing a change in the shelve, the new name will be used.

Title: Python shelve class rename

Body:
Shelve uses pickle to serialize objects. Pickle loads objects by name; the module and class name are stored and looked up when deserialising.

The easiest way to support 'legacy' names is to simply create an alias:

class NewName(object):
    # a renamed object, once named OldName

# backwards-compatible names for unpickling
OldName = NewName

When unpickling, modulename.OldName is looked up and used, which is simply the same class as NewName. When storing a change in the shelve, the new name will be used.


问:
Do SAS coding "best practices" exist?
At work, we develop a lot of our applications in SAS, from start to finish. One of the problems with this approach is that SAS is a very verbose language with very few language constructs; there is limited support for variables, very limited support for basic functions, and no such thing as classes. They have a concept called "macros" which essentially text substitution; you define a macro, and on invocation, it simply drops in the content of the macro.

My question is, is anyone familiar with "best coding practices" for use in developing SAS applications? Are there software design patterns for SAS? I've gone through Code Complete, and some of what he writes is applicable to SAS, but much of it is not, as the concepts don't exist in SAS. Can anyone give recommendations for writing maintainable, well-designed SAS code?

答:
Yes, best practices do exist and are widely known among practitioners. (Of which I am one). Some are being written down by PHUSE on their wiki. http://www.phusewiki.org/wiki/index.php?title=Good_Programming_Practice_Guidance

I think in fact SAS is very OO. But the objects are data tables. They hold metadata, and can be manipulated. For a more formal view you could read 'programming with data' by Chambers for many of the same design goals and justification for objectifying tables.

1 proc step

SAS has two parts -- the high level - domain specific - procs for analytics and most every Statistical modelling. These have (yes, verbose) interfaces. But good defaults and easy to get answers. For example try to program even a simple factorial ANOVA in Fortran, C, C++ or Java.

2 data step

And part two is a low level data manipulation language that predates SQL  that is admittedly sequential but, very fast. It has the property that a program you write will run on any size dataset -- limited only by your disk space - or number of tapes if you have tapes. This differs from all the languages I mentioned and also from most Stats Packages too. (e.g R, without the enterprise big file packages from Revolution Analytics).

The macro language fits in there.

3 However

New tools are here and these are the hash object which can persist and the proc FCMP which can encapsulate code data step and proc step. It can pass values or matrices back to the caller.
See my paper here for more info and references and an assessment of hash objects in a real life case study.

http://www.phusewiki.org/docs/2012/PAPERS/CS/CS05.pdf

Title: Do SAS coding "best practices" exist?


问:
jQuery - When to Bind Event Listeners?
I'm building a medium-sized "single-page" JavaScript application using jQuery. If you include all possible functionality of the application, there are 134 click bindings.

Since most of the content is dynamically loaded, I can't just do this:

$(element).click(function() { ... });

Instead, I'm doing this:

$(document).on('click', selector, function() { ... });

Currently, I'm binding all of these on $(document).ready. But is that bad practice? Is this a speed issue?

The alternative would be to bind the event listeners every time the content is loaded, for example:

```<code>$('#content').html(...);
$('#newcontent').click(function() { ... });
</code>```

The problem with that is it's difficult to organize. What advice can you give me?

答:
You would get a slight increase in performance if you were to bind the events closer to the targets.  As it is now every element within the document is being checked to see if it matches "selector".  For instance, if your page is organized like this:

```<code><div id="container">
   <div id="content">...</div>
</div>
</code>```

You would be better off rewriting

```<code>$(document).on('click', selector, function() { ... });
</code>```

as

```<code>$("#container").on('click', selector, function() { ... });
</code>```

You would achieve the same convenience of not having to re-attach the events, but the action events would be limited to "#container".  Another thing to consider with attaching events to $(document) is that if new items are added elsewhere on the page with the same selector you won't have to worry about them taking on unwanted behaviors.

Title: jQuery - When to Bind Event Listeners?

Body:
You would get a slight increase in performance if you were to bind the events closer to the targets.  As it is now every element within the document is being checked to see if it matches "selector".  For instance, if your page is organized like this:

<div id="container">
   <div id="content">...</div>
</div>

You would be better off rewriting

$(document).on('click', selector, function() { ... });

as

$("#container").on('click', selector, function() { ... });

You would achieve the same convenience of not having to re-attach the events, but the action events would be limited to "#container".  Another thing to consider with attaching events to $(document) is that if new items are added elsewhere on the page with the same selector you won't have to worry about them taking on unwanted behaviors.


问:
What, in reference to DDD, is a bounded context?
When working through the book "Implementing Domain Driven Design" by Vaughn Vernon, I have been unable to gain a good grasp on what a bounded context actually is.

The book defines a bounded context as "a conceptual boundary where a domain model is applicable. It provides Ubiquitous Language that is spoken by the team and expressed in its carefully designed software model" (the "Guide to this Book" prefacing section). This definition would make it sound as though a bounded context is the model and language of a subdomain, where that subdomain may happen to be the core domain (which seems like it ought to be referred to as a "core subdomain", but that is another discussion...). This still leaves some ambiguity as to what a bounded context provides. Is it a grouping of one or more subdomains? If only one subdomain corresponds to a bounded context, what is the bounded context actually telling us?

Chapter 3 of the same book, however, refers to the integration techniques between bounded contexts. This, however, would seem to imply that the bounded contexts are actually software systems or artefacts of some variety.

Martin Fowler briefly discusses the idea of a bounded context (http://martinfowler.com/bliki/BoundedContext.html), but does not really clarify the issue.

At the end of the day, what is a bounded context? Is it a grouping of subdomains? The model and language for a subdomain? The implementation of a subdomain? Without these answers, it seems rather difficult to understand how to decompose a real-life problem space into bounded contexts.

答:
Bounded Contexts and Subdomains exist at different levels.

A Subdomain is a portion of the problem space, it's a natural partitioning of the system, often reflecting the structure of the organisation. So logistics and operations might be separated from invoicing & billing. Eric differentiates core, supporting and generic subdomains according to their business relevance in the given scenario.

Contexts are portions of the solutions space. They're models. It would be a good thing to have them, reflect the domains-subdomains partitioning ...but life isn't always that easy. And you might have bloated legacy domain encompassing everything, or more context in the same subdomain (i.e. old legacy app the replacement app somebody is building).

To have a Bounded Context you need to have a model, and an explicit boundary around it. Exactly what's missing in many data-driven application that use databases to share data.

Another - orthogonal - way to see it may be the following. Ubiquitous Language, the special condition where every term has a single unambiguous definition, doesn't scale. The more you enlarge it, the more ambiguity creeps in. If you want to achieve precise, unambiguous models, you need to make their boundaries explicit, and speak many little Ubiquitous Languages, each one within a single Bounded Context, with a well defined purpose.


问:
Why null pointer instead of class cast?
In Java:

```<code>int count = (Integer) null;
</code>```

throws a java.lang.NullPointerException.

Why doesn't this throw a Class Cast Exception for ease in programmer understanding?

Why was this exception chosen over any other exception?

答: To unbox a Integer into a int i.e. in int i = new Integer(15);, i actually equals new Integer(15).intValue() i  = (Integer) o; where Object o = 15 is the same as o = Integer.valueOf(15); but i = null; throws an NullPointerException because i then equals  null.intValue() which throws a NullPointerException.

Title: Why null pointer instead of class cast?


答:
I believe you're doing it the preferred way (using on).

No real work is being done at $(document).ready ... you're just saying "bind me to any click event from any child element bubbling up to the document".

From a perf perspective, I would just make sure your selector is efficient.

The documentation (http://api.jquery.com/on/) shows binding at the  level rather than document, but that might be negligible.

Title: jQuery - When to Bind Event Listeners?

Body:
I'm building a medium-sized "single-page" JavaScript application using jQuery. If you include all possible functionality of the application, there are 134 click bindings.

Since most of the content is dynamically loaded, I can't just do this:

$(element).click(function() { ... });

Instead, I'm doing this:

$(document).on('click', selector, function() { ... });

Currently, I'm binding all of these on $(document).ready. But is that bad practice? Is this a speed issue?

The alternative would be to bind the event listeners every time the content is loaded, for example:

```<code>$('#content').html(...);
$('#newcontent').click(function() { ... });
</code>```

The problem with that is it's difficult to organize. What advice can you give me?

Body:
I believe you're doing it the preferred way (using on).

No real work is being done at $(document).ready ... you're just saying "bind me to any click event from any child element bubbling up to the document".

From a perf perspective, I would just make sure your selector is efficient.

The documentation (http://api.jquery.com/on/) shows binding at the <body> level rather than document, but that might be negligible.


问:
How to manage focus for a small set of simple widgets
I'm developing a set of simple widgets for a small (128x128) display.

For example I'd like to have a main screen with an overlay menu which I can use to toggle visibilty of main screen elements. Each option would be an icon with a box around it while it is selected. Button (left, up, right, down, enter) events should be given to the widget that has "focus".

Focus is a simple thing to understand when using a GUI, but I'm having trouble implementing this. Can you suggest a simple concept for managing focus and input events? I have these simple ideas:

Only one widget can have focus, so I need a single pointer to that widget.

When this widget gets some kind of "cycle" input (as in "highlight the next item in this list"), the focus is given to a different widget.

a widget must have a way of telling the application which widget the focus is given to next.

if a widget cannot give a "next focus" hint, the application must be able to figure out where the focus should go.

Widgets are currently structured like this:

A widget can have a parent, which is passed to the constructor. Widgets are created statically, as I want to avoid dynamic memory allocation (I only have 16kB of RAM and I'd like to have control over that).

widgets have siblings, implemented as an intrusive linked list (they have a next member). A parent has a pointer to the head of its list of children.

Input events are arguments to the widgets buttonEvent methods which can accept or ignore that event. If it ignores the event, it can pass the event to its parent.

My Questions:

How can I manage focus for these widgets?

Am I making this too complicated?

答:
I think you are making the problem more complicated than it is. Create an array to contain a reference to each widget. Append widgets to the array in the order they are created. The next widget to get focus is just the next widget in the list that is focusable.

You can then add functions to raise and lower the relative ordering of widgets for when you want to traverse them in a different order than they were created.

If you want to get fancy, give each widget a "canAcceptFocus" method, so moving focus means going to loop over the widgets, calling the method until one of them returns true. This way a widget can decide for itself whether it should be focused (such as returning False if its own status is disabled, or if it's just a simple label widget, etc). It doesn't have to know about any other widgets, it just has to know if it can be focused or not.


问:
How long do you spend on analysis? Is this analysis paralysis?
I am not very good at estimating how long a piece of work will take to complete.  I am guilty of putting my finger in the air and guessing.  Usually things are later than expected, however sometimes they are earlier than expected.  For example, a recent individual task was delivered in four months instead of five months.  However, I am usually late.

I want to get better at this.  If I say something will take four months then I want it to take four months or less and not four and a half months or five months etc.

The next task I am approaching was moved to the top of the project plan within the last week because of external pressures (external to the department).  The business area want to know exactly how long it will take to complete.  I find it difficult to estimate because of the following reasons:

The system I develop is very complex.  I inherited it a few years ago and the previous developer did not follow good practice e.g. SOLID, separating layers (business layer etc) etc.

The business requirements are not particularly well understood by the business area because the system is very complex and we have to take into account legislation, which is only guidance and completely open to interpretation.

We lack the appropriate tools e.g. testing framework, continuous integration etc.

I am a sole developer so I have no-one to really turn to for guidance or help e.g. with testing etc.

Anyway I have read questions like this: How to respond when you are asked for an estimate? and this: http://msdn.microsoft.com/en-GB/library/hh765979.aspx.

My manager has suggested that I spend one month doing the analysis for the next piece of work (it is complex).  I think I could do it in a week (I usually only spend a few days).  What should the Agile output of an analysis be? How long do you typically spend of analysis?

答:
If I say something will take four months then I want it to take four months or less and not four and a half months or five months etc.

Well don't we all? You can't, so don't. Not in the environment you described. It's too unpredictable.

You mentioned agile and it is because of this you don't make promises 4 months in advance at least not until you get some of the project built to use as a gauge for the rest of the project. Then you may have to change that estimate. Everyone has to agree to this type of process; not just the developer.

The business requirements are not particularly well understood by the
  business area because the system is very complex and we have to take
  into account legislation, which is only guidance and completely open
  to interpretation

If you don't know what you have to build, how can you give a solid estimate? Manage expectations, "If the requirements don't change, I can do it in 4 months." Document changes and resubmit estimates. Who knows, maybe they can do without that feature?

I understand you take pride in your work and want to deliver on your promises, but this environment doesn't lend itself to that. Things change and stuff happens - estimates are not immune to these facts.


问:
What's an Elegant and OOP way to create a tree from arrays and render it as a nested UL
I have a series of arrays which represent file system paths, so each next value is actually a directory deeper, for example:

```<code>var a1 = ["Desktop", "Pictures", "Summer 2011"];
</code>```

is the equivalent of

```<code>Desktop
|-Pictures
  |-Summer 2011
</code>```

I'm trying to find an elegant way to:

Flatten/merge all the different arrays I have to come up with one object/dictionary/multi-dimensional-array.

Parse the result and render a nested UL (html list) to the page which represents the hierarchy correctly.

Write what I already have in a more 'OOP way'..

I already have a working version:

```<code><!DOCTYPE html>
<html>
    <head></head>
    <body onload="init()">
        <ul id="tree"></ul>
        <script>
            var a = [ "Desktop", "Folder1",  "InnerFolder1" ];
            var b = [ "Desktop", "Folder1",  "Inner 2" ];
            var c = [ "Documents", "Folder 2", "InnerFolder1", "even deepper" ];
            var d = [ "Something Else", "Folder1",  "Inner 2" ];

            var all = [a, b, c, d];
            var Tree = {};
            var ul = document.getElementById("tree");

            function init(){
                for ( var i = 0; i < all.length; i++ ){
                    addToTree(Tree, all[i] );
                }
                createList(Tree, ul);
            }

            //function from http://stackoverflow.com/questions/3663096/how-to-convert-array-to-tree
            function addToTree(tree, array) {
                for (var i = 0, length = array.length; i < length; i++) {
                    tree = tree[ array[i] ] = tree[ array[i] ] || {};
                }
            }

            function createList( obj, _pushTo  ){
                for ( attr in obj ){
                    var _doIHaveChildren = function ( ){
                        for(var prop in obj[attr]) {
                            if (obj[attr].hasOwnProperty(prop)) {
                                return true;
                            }
                        }
                        return false;
                    }
                    var li = document.createElement("li");
                    li.id = attr.toString();
                    li.innerHTML = attr.toString();
                    if ( Tree.hasOwnProperty(attr) ){
                        ul.appendChild(li);
                    } else {
                        _pushTo.appendChild(li);
                    }
                    if ( _doIHaveChildren() === true ){
                        var ul2 = document.createElement("ul");
                        li.appendChild(ul2);
                    }
                    createList( obj[attr], ul2 );
                }
            }
        </script>
    </body>
</html>
</code>```

Thanks!

EDIT:
I'm starting from strings which represent the paths i.e. "Desktop/Pictures/Summer 2011" which are broken to arrays.

答:
I found this to be a very nice solution to creating a tree.  To be more OO, I created a Tree component and the basic part of this became one of its methods. There seems to be a small flaw in the createList function.  If a sub node has the same name as a top node, it will appear as a top node.

I fixed it this way, which also takes greater advantage of the recursive action while passing the  to append to:

```
            function createList( obj, _pushTo  ){
                var ul2;
                for ( attr in obj ){
                    var _doIHaveChildren = function ( ){
                        for(var prop in obj[attr]) {
                            if (obj[attr].hasOwnProperty(prop)) {
                                return true;
                            }
                        }
                        return false;
                    }
                    var li = document.createElement("li");
                    li.id = attr.toString();
                    li.innerHTML = attr.toString();
                    _pushTo.appendChild(li);
                    if ( _doIHaveChildren() === true ){
                        ul2 = document.createElement("ul");
                        li.appendChild(ul2);
                    }//else return
                    createList( obj[attr], ul2 );
                }
            }
```

Body:
I found this to be a very nice solution to creating a tree.  To be more OO, I created a Tree component and the basic part of this became one of its methods. There seems to be a small flaw in the createList function.  If a sub node has the same name as a top node, it will appear as a top node.

I fixed it this way, which also takes greater advantage of the recursive action while passing the  to append to:

            function createList( obj, _pushTo  ){
                var ul2;
                for ( attr in obj ){
                    var _doIHaveChildren = function ( ){
                        for(var prop in obj[attr]) {
                            if (obj[attr].hasOwnProperty(prop)) {
                                return true;
                            }
                        }
                        return false;
                    }
                    var li = document.createElement("li");
                    li.id = attr.toString();
                    li.innerHTML = attr.toString();
                    _pushTo.appendChild(li);
                    if ( _doIHaveChildren() === true ){
                        ul2 = document.createElement("ul");
                        li.appendChild(ul2);
                    }//else return
                    createList( obj[attr], ul2 );
                }
            }


问:
MVC: Does the Controller break the Single Responsibility Principle?
The Single Responsibility Principle states that "a class should have one reason the change".

In the MVC pattern, the Controller's job is to mediate between the View and the Model. It offers an interface for the View to report actions made by the user on the GUI (e.g. allowing the View to call controller.specificButtonPressed()), and is able to call the appropriate methods on the Model in order to manipulate it's data or invoke it's operations (e.g. model.doSomething()).

This means that:

The Controller needs to know about the GUI, in order to offer the View a suitable interface to report user actions.

It also needs to know about the logic in the Model, in order to be able to invoke the appropriate methods on the Model.

That means that is has two reasons to change: a change in the GUI, and a change in the buisness logic.

If the GUI changes, e.g. a new button is added, the Controller might need to add a new method to allow the View to report a user press on this button.

And if the business logic in the Model changes, the Controller might have to change in order to invoke the correct methods on the Model.

Therefore, the Controller has two possible reasons to change. Does it break SRP?

答:
Controllers actually have only one responsibility: altering the applications state based on user's input.

A controller can send commands to the model to update the model's state (e.g., editing a document). It can also send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).

source: wikipedia

If instead you are having Rails-style "controllers" (which juggle active record instances and dumb templates), then of course out are breaking SRP.

Then again, Rails-style applications are not really MVC to begin with.


问:
TDD for batch processing: How to do it?
I like "red/green/refactor" for RoR, etc. just fine.

My day job involves batch processing very large files from third-parties in python and other custom tools.

Churn on the attributes of these files is high, so there are a lot of fixes/enhancements applied pretty frequently.

Regression testing via a known body of test data with expected results does not exist.  Closest thing is running against the last batch with new test cases hand coded in, make sure it does not blow up, then apply spot-checking and statistical tests to see if data still looks OK.

Q>> How to bring TDD principles into this kind of environment?

答:
Start with a good software strategy, then apply TDD.

(Disclaimer: I may have misunderstood "churn", or TDD, or both.)

Here is my suggested strategy for batch processing "dirty data": Specify-Triage-Execute.

Draft a specification of the data in a stringent and narrow way, yet will cover the majority (say, 80% or more) of the incoming data. Call this Specification 1.

Develop a Triage module (TDD if you wish) that decides if a record meets Specification 1.

Make sure the module runs very fast.

The module should return true/false: it either meets all of the rules, or it doesn't.

Develop an Execute module (TDD if you wish) that parses a record that is known to meet Specification 1, performing whatever tasks needed by your customers.

Apply Triage 1 on all incoming data.

The result is one boolean value for each record. This basically separates the incoming data into: Specification 1, or Unknown.

Apply Execute 1 on the Specification 1 data, whenever needed by the customer.

Relax the rules of Specification 1 in order to admit 80% of the remaining data. Call this Specification 2.

Develop Triage 2 and Execute 2. Apply it to any data that did not meet Specification 1.

Repeat for as many levels as needed, until the remaining data is small enough that it can be manually processed every day.

The efficiency tidbit:

Save all of the Triage results (historical or current) associated with a record. If no Triage modules are modified since the last run, then it does not have to be re-run on old data.

The "you have to know what you want to build before doing TDD" tidbit:

The Specify-Triage-Execute is one way to keep the requirements manageable on each level and allows for future growth.

(If any knows the standard correct terms for those three steps, please let me know, I'll edit my answers.)

Title: TDD for batch processing: How to do it?


问:
Progressive Enhancement vs. Single Page Apps
I just got back from a conference in Boston called An Event Apart.

A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.

The arguments that the speakers gave for progressive enhancement were very compelling. Not only is it a solid pattern for supporting older browsers, and devices on a network with low bandwidth, but HTML fails much more gracefully than JavaScript (i.e. markup that is not supported is just ignored, while if a browser throws an exception while executing your script - you are hosed).

Jeremy Keith gave a particularly insightful talk about this.

But what about single page web apps like Backbone and Angular? The whole design behind these frameworks seems to push the developer toward moving content out of the HTML, and into something like a JSON API.

I can not seem to gel these two design patterns: progressive enhancement vs. single page web apps. Are there instances when one is better than the other? Or are they not even antagonistic technologies, and I am missing something here with my mental model?

答:
It seems to me that single-page apps draw a line in the sand of progressive enhancement. Where before we might try to work around the fact that implementations and features vary between browsers going back for decades, SPAs assume that there's a certain baseline that we can reasonably agree most visitors of a given site will meet. I don't think the two are at odds. You can still continue to progressively enhance after the SPA starts, like starting with a <video> tag, then layering your own feature-rich player on top of that.

Then there are visitors with scripting disabled, but they know what they're getting into. I don't see why developers should bend over backwards for those visitors, aside from a "You need scripting for this site" note. If we allow that, why not also cater to visitors with CSS disabled? How about images disabled? These are core web technologies. They should not expect to have a fully functional web experience when they go picking and choosing pieces.

To ensure I don't get away without a car analogy, I should not expect my car to work if I decide I don't like certain features. I could tell civil engineers, "I disabled my headlights, so please make sure to install street lights every 125 feet everywhere I might visit." Without headlights, my car would work a lot of the time, but some places I'll be unable to visit.


答:
SPA is most beneficial if you are creating an application that does not fit the classical request/response pages model. There are a recent trend where regular websites are written as a SPA even when they fit just fine into the request/response cycle of the web, IMHO what they are doing are foolish endeavours. What the likes of these websites are doing is poorly reimplementing a web browser with lots more bugs and less features.

The idea of progressive enhancement and SPA is not mutually exclusive for these foolish single-page appli-websites. You simply need the javascript to do some content negotiation (i.e. Accept header) so they receive JSON resource that the Javascript on the SPA can render themselves instead of a pre-rendered HTML pages. The issues with this kind of website SPAs is obvious, you have to have duplicate implementation of the website's rendering on both the server and on the client.

For true web applications, i.e. one that truly have to be an SPA as they don't fit into the standard request/response pattern; progressive enhancement is much more difficult for true applications because they are really just using a browser as a technology platform for writing an application portably. Scripting language is an essential part of a true web application, not just one that can be optionally bolted for enhancements. Some progressive enhancements techniques still can work though (e.g. replacing flash video/audio with <video>/<audio> tag) but true web applications will require javascript as a baseline.

Title: Progressive Enhancement vs. Single Page Apps

Body:
I just got back from a conference in Boston called An Event Apart.

A really popular theme amongst the speakers was the idea of progressive enhancement - a site's content should go in the HTML, and JavaScript should only be used to enhance behavior.

The arguments that the speakers gave for progressive enhancement were very compelling. Not only is it a solid pattern for supporting older browsers, and devices on a network with low bandwidth, but HTML fails much more gracefully than JavaScript (i.e. markup that is not supported is just ignored, while if a browser throws an exception while executing your script - you are hosed).

Jeremy Keith gave a particularly insightful talk about this.

But what about single page web apps like Backbone and Angular? The whole design behind these frameworks seems to push the developer toward moving content out of the HTML, and into something like a JSON API.

I can not seem to gel these two design patterns: progressive enhancement vs. single page web apps. Are there instances when one is better than the other? Or are they not even antagonistic technologies, and I am missing something here with my mental model?


问:
Is there a metric that can be equated to complexity in laymens terms?
Often times users cannot comprehend the complexity of software.  They think that because a problem is easy to describe then it is easy to solve.  I want to equate the complexity of a "simple program" I have built with the complexity of a process with a tangible result.

Is there a system that can take tangible processes and assign them a complexity such as:

Building an outhouse = 5

Building a house = 50

Building the empire state building = 5000

that I can then equate to the software in a meaningful way:

thisProject = 5

Maybe the project weight is determined by Cylcomatic Complexity.  Whatever it is is not that important.  What is important is that such a system exists.  Does such a system exist?

Update

I'm looking for a means to compare the complexity of two complete systems.  I am not looking for estimation methods. The limitation I see in using "money and man hours" is that the laymen (or maybe even somewhat technical) individual could attribute the reason the project took so long and cost so much money is because the developer(s) were simply not good at their jobs.

Thinking out a possibility...

I imagine a solution to this problem could be similar to Dijkstra's algorithm.  Create a flowchart for System1 and another for System2.  Give each decision a weight based on how many routes the decision contains.  Give each action a weight as well.  The cumulative weight of each respective chart can then be used to compare the two processes.

For the "tangible process":
If some engineer mapped a flowchart for "building an outhouse" then we could use such an algorithm to obtain a "total weight" for the process.

For the "intangible process":
Assuming the entire program can be mapped to a Finite State Machine then it can be described as a flowchart and assigned a weight as well.

So the outhouse process is weighted at 50 and "my program" is weighted at 60. So it's about as complex as building an outhouse.

答:
The closest approximation is time. If a system is small but takes a lot of time, that is typically due to its complexity. However, this is a very difficult metric to capture.

What I have found helpful is to estimate the project. Break that estimate down into pieces. The idea is to break it down into the smallest pieces that make sense, which are normally stories in the Agile methodology.

Nobody can really comprehend that a system requires 5,000 hours of work to complete. That is too big of a number. But break that down into individual stories and each one is easier to digest. If a story is complex and requires more time, that will be easier to explain at the story level than at e.g. the epic or system level.

It is one thing to say that a skyscraper is a complex building: I think we as laymen can agree to that fact, but it is difficult to explain why. It is more meaningful to say that a subcomponent is complex. For example, the electrical system is complex because there will be 5,000 separate offices in the building that are metered individually. The sewage system is complex because there will be 400 restrooms in a vertical building that have to be vented properly.

When you decompose a large problem into small ones, it becomes easier to attach estimates to them as well as to explain why a component is complex.

So no, there is no silver bullet number you can use to gauge complexity. However, you can decompose a problem into smaller, easier to understand pieces and explain those.


问:
Back button after doing posts on the same page
I have 3 pages to my site. The 1st page allows you to select a bunch of options. Those options get sent to the 2nd page to be displayed with some data about those options. From here I can click on a link to get to page 3 on 1 of the options. On page 3 I can create a new/edit/delete all on the same page where reloads come back to page 3.

I want a "back" button on page 3 to go back to page 2, but retain the options it had from the original page 1 request. Page 1 has a bunch of check boxes which are passed to page 2 as arrays to the controller. My thought is that I have to pass these arrays (I converted them to lists) to page 3 (even thought page 3 directly doesn't need them) so that page 3 can use them in the back link to it can recreate the values page 1 sent to page 2 originally.

I'm using asp.net MVC and when I pass the converted array it seems to convert it to the type instead of actually showing the values: "types=System.Collections.Generic.List" (where types is a List.

Is this what is needed or are there other options to getting a "back" button in this case to go back to page 2. It's sort of a pain to pass information to page 3 that isn't really relevant to page 3 except the back button.

答:
There's a couple ways of handling this.

On Page 1, you can post the form to itself (Page 1), and then if everything gets saved correctly, store the posted data in the session and then redirect the page to Page 2.  Page 2 gets generated from the session information, not the data posted to it.

Another way would be to post the form via AJAX, store the posted info in the session on the server, and then redirect to Page 2 after the AJAX call completes.

Either way, when on Page 3, you should then be able to 'page back' to Page 2 without having to refresh the page because Page 2 was not the result of a POST.


问:
What does it mean when data is scalar?
I don't know what scalar means exactly, but I'm trying to see if I'm thinking about it correctly. Does scalar relate to arbitrariness where the type of data could be any type, or a system is not able to know what the data is in advance. </p>

答:
A Scalar is simply a variable that holds an individual value.  For purposes of this discussion, let's assume that a scalar is a single number, rather than a collection of numbers.

For example the result of a SQL query that returns a number instead of a tuple, as does the ExecuteScalar() method in the SQLCommand class, which returns the value of the first column of the first row in the result set returned by the query.  It's typically used to retrieve an aggregate value such as a COUNT or AVERAGE, the ID of a new record, or the number of records processed by a query.

Title: What does it mean when data is scalar?


问:
How can I hide my signature in a program?
We have a university programming course and fellow students are asking some programming questions in our Facebook group. I'm a little hesitant to share all of my programs, especially if it's something cool for one of the assignments, since these are looked at by the TAs and they might notice if somebody has the same program and start asking questions on where it came from. Still, sometimes I'd like to share my code to help others, but I don't wanting people just grabbing my work.(Clarification: We are allowed to collaborate with the tasks) This is of course a thin line. While I want to help some people, I'm concerned that they may not have the academic honesty to rewrite the code on their own.

Most of my fellow students are not very advanced in their skills, so I'd get away with say hiding my name in Base-64 encoded string crafted into a discrete place. Still, it may be too obvious for a random string to be sitting around.

What options exist to hide my name in a program without it looking suspicious?

I've seen over at CodeGolf that they have made ascii art turn into other things when evaluated. Are there similar strategies I could utilize? The ideal solution would be something that looks like something that fits in discreetly but in reality has a function to prove that I coded it from the beginning.

Clarification: (Sorry, should have said this earlier) We're allowed to collaborate but have to explain our programs to the TAs to get the points. It's just for satisfaction to hide some Easter Eggs in other's code if it leaks out, especially since it may be tempting to exchange programs to check that the answers to problems they generate are equivalent etc or to see how others solve the problem.

答:
You could also use one of the oldest tricks in hiding messages. Make the first letter of each variable hide a message. For example,</p>

```<code>$Image = "test";
$a = "/test/img.jpg";
$message = "This is img.jpg";
$Full = 435674;
$rate = 3;
$ascii = "---....!--";
$number = 2040;
$k = 5;

// Do some work here?
</code>```

Body:
You could also use one of the oldest tricks in hiding messages. Make the first letter of each variable hide a message. For example,

$Image = "test";
$a = "/test/img.jpg";
$message = "This is img.jpg";
$Full = 435674;
$rate = 3;
$ascii = "---....!--";
$number = 2040;
$k = 5;

// Do some work here?


答:
A scalar is a simple single numeric value (as in 1, 2/3, 3.14, etc.), usually integer, fixed point, or float (single or double), as opposed to an array, structure, object, complex vector (real plus imaginary or magnitude plus angle components), higher dimensional vector or matrix (etc.) data type that contains more than one single numeric value.

However, note that a large very complex data type of the sort that can also be flattened and represented in 8-bit bytes of computer memory can also be represented as one single very long/large binary scalar number.  Turing used this technique to represent entire computer programs as just one scalar number.

Title: What does it mean when data is scalar?

Body: I don't know what scalar means exactly, but I'm trying to see if I'm thinking about it correctly. Does scalar relate to arbitrariness where the type of data could be any type, or a system is not able to know what the data is in advance. </p>


问:
Why std::allocators are not that popular?
With the latest trends about C and C++ applications, and with latest I mean the latest years, I was expecting to see std::allocators to be used way more frequently than what it really is.

Modern applications are usually multithreaded or with form of concurrency in them, and they manage a significant amount of memory, especially in some fields like games and multimedia applications; so the usual high cost of the allocation/deallocations rises and impacts the performances even more than in old applications.

But for what I can see this kind of memory management through std::allocators is not popular, I can't even count 1 library that I know of, that is using any rationale about a standardize way of managing memory.

There is a real reason why std::allocator is not popular ? Technical reasons ?

答:
There are sort of two questions here:

1) Why isn't std::allocator used more?

The short answer is because for most uses, using new and delete is sufficient.

First, a brief overview of what the C++11 Allocator concept is intended for.  Basically, when you do a new Foo, it both allocates memory and then constructs the object in that memory.

But what if you needed to allocate memory and construct as two separate steps.  The classic example of this is std::vector, which can allocate memory without initializing it immediately, but then constructs the elements as you add them to the container.  The point of std::allocator is to provide an interface for doing those separate steps in a uniform way.

However, for most users, they don't need that level of control, because it's just another thing to remember to do when cleaning up your exceptions.

2) Why don't more things make use of the C++ concept of Allocator?

Mostly the need isn't there.  The only classes that tend to use them are the ones that want to give their users more control over the source of the memory they allocate.  The Standard library containers are written that way so that the user can make those decisions if they choose, but they default to using the normal allocator.


答:
Cartographers have the same problem. A couple techniques:

Introduce an improbable deviance from your language's traditional style, e.g. always have imbalanced spaces around operators

if (lefthand== righthand)

Scatter no-ops throughout your code, if they're part of the language you're using.

lefthand = righthand;;


答: The term "scalar" comes from linear algebra, where it is used to differentiate a single number from a vector or matrix.  The meaning in computing is similar.  It distinguishes a single value like an integer or float from a data structure like an array.  This distinction is very prominent in Perl, where the $ sigil (which resembles an 's') is used to denote a scalar variable and an @ sigil (which resembles an 'a') denotes an array.  It doesn't have anything to do with the type of the element itself.  It could be a number, character, string, or object.  What matters to be called a scalar is that there is one of them.

Title: What does it mean when data is scalar?


答:
Not really.

So far, EVERY software complexity metric that has been proposed has been shown, on real data from real projects, to be strongly to very strongly correlated with raw SLOC: raw number of source lines of code.  McCabe's Cyclomatic Complexity turns out to be noteworthy in its guilt on this, with all of Halstead's metrics running close on its heels.

You could make a fancy metric, and say programs with a McWizzBang value of 42 are more complex (or complicated) than programs with McWizzBang = 7, but you're really just saying that a program with a million lines of code is more complex than a program with a thousand lines of code.  Well, DUHHHH!

Incidentally, although you weren't asking about it, the same is true for software cost estimation.  No matter what you try to estimate, to get to your cost estimate, it turns out that you can get the same bang for a lot less buck by estimating raw SLOC.

Title: Is there a metric that can be equated to complexity in laymens terms?

Body:
Often times users cannot comprehend the complexity of software.  They think that because a problem is easy to describe then it is easy to solve.  I want to equate the complexity of a "simple program" I have built with the complexity of a process with a tangible result.

Is there a system that can take tangible processes and assign them a complexity such as:

Building an outhouse = 5

Building a house = 50

Building the empire state building = 5000

that I can then equate to the software in a meaningful way:

thisProject = 5

Maybe the project weight is determined by Cylcomatic Complexity.  Whatever it is is not that important.  What is important is that such a system exists.  Does such a system exist?

Update

I'm looking for a means to compare the complexity of two complete systems.  I am not looking for estimation methods. The limitation I see in using "money and man hours" is that the laymen (or maybe even somewhat technical) individual could attribute the reason the project took so long and cost so much money is because the developer(s) were simply not good at their jobs.

Thinking out a possibility...

I imagine a solution to this problem could be similar to Dijkstra's algorithm.  Create a flowchart for System1 and another for System2.  Give each decision a weight based on how many routes the decision contains.  Give each action a weight as well.  The cumulative weight of each respective chart can then be used to compare the two processes.

For the "tangible process":
If some engineer mapped a flowchart for "building an outhouse" then we could use such an algorithm to obtain a "total weight" for the process.

For the "intangible process":
Assuming the entire program can be mapped to a Finite State Machine then it can be described as a flowchart and assigned a weight as well.

So the outhouse process is weighted at 50 and "my program" is weighted at 60. So it's about as complex as building an outhouse.


问:
How do I access databases from a mobile device securely?
I have been doing some research on accessing a DB from mobile devices. There are so many different ways of doing it. There are also multiple ways to make it secure. What is a good way to access a database from a mobile device securely?

Also considering my specific case, where I have an existing WCF service which does everything I would need for the app, I would like to re-use it. I have been working on using jsonp calls to the service and develop apps for iOS, Android and windows phone. The calls are secured by HTTPS and I would be implementing some authentication policy for the calls. But how secure would all this be?

I have some really sensitive data to worry about. I am using HTML5 and JS for app development to keep it uniform and less difficult to manage for all platforms.

How do I access the database and keep my data secure?

答:
It's best to not think of making your application "access a database" - your client application logic should be separated from the specifics of the database implementation.  The client simply needs to make requests to a server & let the server handle the details of talking to the database for you.

If we step back a bit and ignore that the client is a mobile device, what you want is basically the standard 3-tier software architecture.  That is you have a relatively 'dumb' client that communicates with a middle layer that manages the business logic & talks to the database for you.  This simplifies your client & allows you to focus on placing security in the middle layer - even if your communications get compromised, a message from a client will never delete all the users if you have no "delete all users" method in your middle tier.

It sounds like you're well on your way, with WCF services to handle client/server communications.  Just make sure to think of your client's requests to the server in terms of what the results should be & not the specific steps to get those results and you'll have a pretty clean system.

I don't know much about WCF but there's probably loads of articles on how to properly secure it, if the functionality isn't already built in.  Just make sure that you never trust the client to do the right thing and always have your server make sure requests are valid before performing them and you should be golden.


答:
Most programming projects contemplated by a single person or small team are not characterised by their complexity, they are better characterised simply by their size.

To estimate something by its size:

find a typical "unit"

estimate the time taken to build one "unit" as T

count the number of "units" as N

multiply N x T

if there are multiple kinds of units, repeat for each and add together

add on some fudge factors for integration, complexity, overruns, rework, etc.

A basic small business system might have 20 forms, 30 database tables, 10 reports, 2 connections to other systems. The final result might be 10,000 lines of code. It might take 200 pages of documentation. Any of these can be used as "units".

Show the customer the list of "units", the count and estimate for each and the total. Then compare it to a big house or a small apartment block with similar numbers of "units".

Size matters more than complexity, but it's still much harder to write a compiler or a framework library than a basic business system and the "units" are much harder to identify.