问:
Designing access to file-based "database"
It happened frequently that I have to provide access to a bunch of files organized in a directory tree according to some (sometimes loosely specified) rules. My standard pattern is to provide a Database class which is initialized with the root directory. This class provides getX()-like (example: getStructure()) methods to extract data from the database. These methods normally return semantically meaningful objects (Structure) with proper methods returning data (eg. structure.getPoints()). I am not completely happy with this design, for two main reasons.

The first problem is that the mapping between in-application objects and files may not be 1:1, that is, to create the Structure object I may have to open different files in the "database", and the mapping may not be perfect. In this case, I call the Structure a "Thick object". An alternative ("thin objects") is to stick to objects that are fully represented in a file, even if poor in high-level domain meaning (that is, if I have two files to define a structure, one file containing points, and the other containing connections between these points, I just provide a Points object and a Connections object, and let someone else "connect the dots" outside Database).

The other problem I have is the following: who should perform the actual file parsing? I envision two strategies: either the objects are able to deserialize themselves from file ("pickle-like" in python parlance), or they are just dumb data containers filled by stateless parser objects (one per file), or even by the database object itself.

When you do ORM, there are clear, well defined rules on how the object is represented in the database, and the process is extremely well defined in terms of interface and behavior. This is not necessarily verified with an arbitrary bunch of files some people call "database".

I would really enjoy your points on this regard. How should I perform proper deserialization in this case of "raw mapping"? Thin or thick objects ? Smart or dumb ?

Note that I don't really have any control at all when it comes to the files I have to access. I get the files from external sources, and I have to convert them into some kind of domain objects, generally only for reading, but sometimes also for writing. Readonly is by far the most frequent case though.

答:
I do this by serializing and deserializing objects using XML.  This allows you to define your rules by how you structure your classes.

Some simple ToXml() and FromXML() helper methods do all of the heavy lifting.

So, for example:

```<code>public class MyRecord
{
    [XmlAttribute]
    public string Foo { get; set; }

    [XmlAttribute]
    public int Bar { get; set }

    [XmlAttribute]
    public double Baz { get; set; }
}
</code>```

results in XML that looks more or less like this:

```<code><MyRecord Foo="ABC" Bar="123" Baz="123.45">
</code>```

You can make this as elaborate as you want, using composition to nest objects within other objects, and so forth, creating tree-like structures, or even collections.

```<code>public class MyRecordTree
{
    public MyRecordTree Node { get; set; }
    public List<MyRecordTree> Children { get; set; }
}
</code>```

Body:
I do this by serializing and deserializing objects using XML.  This allows you to define your rules by how you structure your classes.

Some simple ToXml() and FromXML() helper methods do all of the heavy lifting.

So, for example:

public class MyRecord
{
    [XmlAttribute]
    public string Foo { get; set; }

    [XmlAttribute]
    public int Bar { get; set }

    [XmlAttribute]
    public double Baz { get; set; }
}

results in XML that looks more or less like this:

<MyRecord Foo="ABC" Bar="123" Baz="123.45">

You can make this as elaborate as you want, using composition to nest objects within other objects, and so forth, creating tree-like structures, or even collections.

public class MyRecordTree
{
    public MyRecordTree Node { get; set; }
    public List<MyRecordTree> Children { get; set; }
}


问:
What's the best way to learn nature-inspired algorithms?
I completed the Machine Learning course (Stanford) and got very interested, also after some research, I decided that I'd like to learn nature-inspired algorithms.

I've found some resources like:

Clever Algorithms: Nature-Inspired Programming Recipes (Book)

Wyss institute (Website)

Programming Game AI by Example (Book)

The first reference look good and complete with pseudocode (giving me the possibility to implement everything in Ruby, my prefered language), and also gives ruby implementations for every code. But it lacks of exercises to practice, which I think is a key feature.

The second is something that inspired me a lot to start studying this area, but they don't have any course or material to study.

The third one looks good too, but has only a little amount of exercises, and might be too focused (I do like games, but I also want to study everything else related to nature-inspired algorithms). Also it is focused on C++ (not that it is a hard language, but I don't like its limitation compared to ruby), and I'd prefere something in Ruby or pseudocode (although it is not my main priority).

Does anyone know something that also have exercises to complement the theory?
Is there anything better to learn, with a particular focus on exercises? (Maybe courses or video lectures).

答: Here is a treasure trove of leads for you.  In particular, I would recommend this book to you.  The author, Xin-She Yang, knows what he is talking about and the book is relatively cheap.</p>

ContentLicense: CC BY-SA 3.0


问:
Choosing a licence for open source projects
I've done some open source projects, and I plan to do more in the future. So far, I've released all my code under GPL, but I've read a few articles which claim GPL is too restrictive for any code to be used in corporate environment. This, supposedly, reduces contributions.

Here's what I wanted to accomplish:

For full applications:

no commercial use with the exception of selling support for the application (i.e. the app cannot be sold, but everything around it can)

For libraries (components, plugins, ...):

can be included into commercial projects without modifications

any modification the the library/component must be open sourced (contributed back) - the rest of the project, commercial or not, is not affected

For applications, GPL still seems the logical choice. For libraries, my primitive understanding of licences makes me think that LGPL is a good match, but, I'm not sure. I've looked at MIT licence, and that seems too permissive.

Most of the time, I want people to use my code anywhere they want to, as long as any improvements are contributed back.

This brings me to my question(s): is LGPL a logical choice for open source libraries, components, plugins etc? Is there a better alternative? Is GPL a good choice for my applications or is there something better?

Update:

For those who are interested in my final decision, I've decided to release my libraries under multi-license scheme, MPL, LGPL and GPL. This enables virtually everyone to use my code with no obligations, unless they modify it under MPL, in which case it would have to be contributed back.

This means the code can be used by both FSF and proprietary software, but "bad" commercial exploitation is prevented (or so I'd like to think).

答:
no commercial use with the exception of selling support for the application (i.e. the app cannot be sold, but everything around it can)

Beware that the GPL doesn’t forbid selling the application, and forbidding this would indeed render your license non-free, as observed by Huperniketes. The only thing the GPL ensures is that the company selling the software would also have to provide the code base for free. But they don’t have to provide the software package as-is for free. That’s quite a big difference, since the source code of a software is not a readily usable product.

ContentLicense: CC BY-SA 2.5


问:
In Functional Programming, should domain-relevant simple functions (e.g., sorts) be reified?
In a functional application, should you wrap common higher-level functions in domain-meaningful names or should you leave them "bare"?

For instance, if you have a list of Addresses, and "sorted by zipcode" is a common domain-meaningful ordering (targeted mailers, etc.), is it preferable to write:

```<code>val sortedCustomers = customers.sort((a,b) => (a.zipCode compareTo b.zipCode) < 0)
</code>```

Or is it better to create a function sortedByZip(cs : Iterable[Customer]) : Seq[Customer]?

Creating the function has the advantage of being (minutely) more abstract, but has the disadvantage of being opaque, creating a name to remember, etc.

I'm asking in the context of a significant professional codebase, one that you intend to live for years, be as maintainable as possible, be "true" to the expectations of functional programmers, etc.

答: It depends (but then, you knew that). If this call site is the only place customers are sorted, then I'd leave it as is for the moment. If the sorting code were more complicated (CC > 1), I'd definitely extract a function for the sorting criterion. If I had ten call sites like the one above, I would definitely have a sortedCustomers() function. Somewhere between 1 and 10 (really between 2-4, assuming I noticed the duplication), I'd extract the function.</p>


问:
Continuous Integration : which frequency?
I've always launched builds after each commit, but on this new project, the architects just asked me to change the frequency to "one build every 15 minutes", and I just can't understand why that would be a good reason vs "building on each commit".

First off, some details :

Objective-C (iOS 5) project

10 developpers

each build actually takes ~1 min, and includes build and unit testing.

the integration server is a Mac Mini, so computing power isn't really a problem here

we use Jenkins with the XCode plugin

My arguments were that if you build at each commit, you can see right now what went wrong, and correct directly your errors, without bothering the other devs too often. Plus our tester is less bothered by UT errors this way. His arguments were that devs will be flooded by "build error" mails (which is not completely true, as Jenkins can be configured to send a mail only for the first broken build), and that metrics can't be done properly if the frequency of builds is too high.

So, what's your opinion on this ?

答:
You said you can't understand their reasoning, so you have to ask them. Don't just guess at what they want and try to implement that, and certainly don't just implement what they asked for without understanding why they asked for it.

That said, to answer the general question, it depends on the development philosophy you use. If every commit is expected to work, then every commit should be tested. If you use a DVCS with the philosophy that every push should work, then test every push.

In general, it's better to tell people something they don't know, then to repeat what they do know. For example, if they want to reduce the number of redundant emails they get, tweak the email settings, not the build frequency.


问:
Examples of operator overloading, which make sense
While I learning C#, I found that, the C# supports operator overloading. I have problem with good example which:

Make sense (ex. adding class named sheep and cow)

Is not an example of concatenation of two strings

Examples from Base Class Library are welcome.

答:
They're not in the category of things that people typically think of when they thing of operator overloading, but I think one of the most important operators to be able to overload is the conversion operator.

Conversion operators are especially useful for value types that can "de-sugar" to a numeric type, or can act like a numeric type in some contexts.  For example, you might define a special Id type that represents a certain identifier, and you could provide an implicit conversion to int so that you can pass an Id to a method that takes an int, but an explict conversion from int to Id so no one can pass an int into a method that takes an Id without casting it first.

As an example outside of C#, the Python language includes many special behaviors that are implemented as overloadable operators.  These include the in operator for membership testing, the () operator for calling an object as if it's a function, and the len operator for determining the length or size of an object.

And then you have languages like Haskell, Scala, and many other functional languages, where names like + are just ordinary functions, and not operators at all (and there is language support for using functions in infix position).


问:
Is HTML5 more secure to develop for than Silverlight?
I'm learning Silverlight, and I know that if I master it, I can apply the same concepts to WPF, which means I can do either web or desktop development pretty easily. But I've read articles and followed the discussion online, and I understand HTML5 is gaining traction for being cross-platform, and a lot of people seem to be moving to HTML5.

From my understanding, any HTML5 application would be built with HTML and JavaScript (or Flash). But is it secure? It seems like anyone can easily use their browser's "view source" option and grab your code. Is this something I should be worried about, or is there a way to protect against it?

答:
Anything you want to protect needs to be kept on the server, end of story.

This goes for any of the web technologies - HTML, Flash, Silverlight, etc.  Anything downloaded to the client can be stolen easily.


答:
The key here is to have layers with well-defined interfaces.  The lowest layer deals strictly with physical access to the files.  It handles things like caching, concurrent access, opening, flushing, etc.  Its interface allows higher layers to retrieve one line at a time without having to worry about things like if the file is already open.

The second layer provides dumb data structures to work with.  Its interface would basically consist of a bunch of records with columns of simple data types, all of which are contained within a single file.  Rows of the database, if you will.

The third layer provides smart objects to work with.  It aggregates the database rows from multiple tables to make objects with friendly interfaces.

Title: Designing access to file-based "database"

Body:
It happened frequently that I have to provide access to a bunch of files organized in a directory tree according to some (sometimes loosely specified) rules. My standard pattern is to provide a Database class which is initialized with the root directory. This class provides getX()-like (example: getStructure()) methods to extract data from the database. These methods normally return semantically meaningful objects (Structure) with proper methods returning data (eg. structure.getPoints()). I am not completely happy with this design, for two main reasons.

The first problem is that the mapping between in-application objects and files may not be 1:1, that is, to create the Structure object I may have to open different files in the "database", and the mapping may not be perfect. In this case, I call the Structure a "Thick object". An alternative ("thin objects") is to stick to objects that are fully represented in a file, even if poor in high-level domain meaning (that is, if I have two files to define a structure, one file containing points, and the other containing connections between these points, I just provide a Points object and a Connections object, and let someone else "connect the dots" outside Database).

The other problem I have is the following: who should perform the actual file parsing? I envision two strategies: either the objects are able to deserialize themselves from file ("pickle-like" in python parlance), or they are just dumb data containers filled by stateless parser objects (one per file), or even by the database object itself.

When you do ORM, there are clear, well defined rules on how the object is represented in the database, and the process is extremely well defined in terms of interface and behavior. This is not necessarily verified with an arbitrary bunch of files some people call "database".

I would really enjoy your points on this regard. How should I perform proper deserialization in this case of "raw mapping"? Thin or thick objects ? Smart or dumb ?

Note that I don't really have any control at all when it comes to the files I have to access. I get the files from external sources, and I have to convert them into some kind of domain objects, generally only for reading, but sometimes also for writing. Readonly is by far the most frequent case though.


问:
Proper terminology for a small set of tightly coupled classes?
What is the proper terminology for a small (2-4) set of tightly coupled classes? These classes can't work independently.

I was thinking system, but after googling for a bit, I've determined that the word is typically used to describe the software as a whole.

Then, I thought of subsystem, but I don't know if the term applies if the number of classes in the subsystem is small.

What do you guys think? This is for a presentation for a professor who wants me to provide definitions for everything.

Edit:

Essentially, I am describing various ways to architect game object systems, found in game engines. I'm using the term system as a way to include all the classes involved in the game object apparatus. Calling it a game object system feels right to me, but I'm not sure if it is the right terminology.

I don't view game objects as a layer, since it doesn't really work as a layer in a game engine. A module or package, to me, seem more suitable for a bunch of purely functional or stateless classes.

If I am not making sense, please let me know!

答: I would say module or package as a generic term, but be careful because in some programming languages or systems these terms have more specific technical meanings.  Layer is also commonly used to denote a set of classes, assuming your code is architected with restrictions like only having knowledge of the layer immediately below you.


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答: That programmers sitting on slow hardware would write faster applications is equivalent to arguing that race car engineers equipped with crappy tools would make faster vehicles.</p>


问:
Should developers enter bugs into the bug tracking system?
While developing (either features or bug fixes) I sometimes happen to discover bugs that are not directly related to what I'm working on.  What should I do in that situation.  Just fix it?  Try to remember to fix it later?  Write it down somewhere?  Or enter it into the bug tracking system?

I generally enter it into the bug tracking system and let the process play itself out (i.e. triaging, assigning, etc.).  However I have hardly ever seen another developer enter a bug.  (Why is that?)

答:
I believe that if a developer encounters a bug that is not related to what they are working and that they will not be fixing, they should enter it into the system just to have some record of it. That way, when QA starts testing (and they're still not fixed) you can give them this list bugs as "known defects" so they don't start reporting the same bugs.

Perhaps other developers who find bugs keep track of it on their own if they plan to fix it, but in that case they run the risk of 2 developers independently finding and fixing the same bug.


答:
If you discover a bug, I can't think of any good reason not to enter it into the bug tracking system, whether you fix it or not.  That's what the bug tracking system is for, after all.

In some cases it might make more sense to report it to a QA person who has more experience dealing with the system, but in any case the bug should be tracked.

It's possible that there might be some reason, valid or not, that developers shouldn't be entering bugs.  One possible reason might be that the bug tracking system is visible to outsiders, and having too many reported bugs looks bad.  That's a very bad reason, which should be addressed in some other way that still allows bugs to be tracked.  Ask your boss.

(Of course if there's a bug in code that you're still working on, and it doesn't show up in anything that's been released, there's no need to track it in the system, though a TODO comment in the source code may be a good idea.  To take an extreme case, "This code won't compile because I haven't yet typed the semicolon at the end of this line" is not a reportable bug.)

As for why other developers don't enter bugs, you'll need to ask them.  They probably should.

Title: Should developers enter bugs into the bug tracking system?

Body:
While developing (either features or bug fixes) I sometimes happen to discover bugs that are not directly related to what I'm working on.  What should I do in that situation.  Just fix it?  Try to remember to fix it later?  Write it down somewhere?  Or enter it into the bug tracking system?

I generally enter it into the bug tracking system and let the process play itself out (i.e. triaging, assigning, etc.).  However I have hardly ever seen another developer enter a bug.  (Why is that?)


答:
Why is that? Because most developers look at the issue they have to raise and the code they have to write and figure it's easier not to bother.

But, whether that's the right thing to do depends on your process. Do you have a QA team? Do you think they mind if you just go changing code which won't be tracked? What about code-reviews? Will it skip by that crack? What about the business? Do they need to know you've fixed a bug so that they don't raise the same one later?

What about other developers? What if they fix it in a different way at the same time? What if they find a similar bug later and all you can do is say "oh, damn, I know we've had something like this before -- now what was it?"

There are about a million reasons for recording bugs in the bug-tracking system. If you're SURE you don't hit any of those issues then by all means, don't bother. But if you're at all unsure then you should record it, even if most people don't.


答:
You must enter the bugs in the bug tracking system in both cases:

when the bug concerns directly the code you are working on,

when the bug concerns the code you're not working on right now or the part on which another developer works.

This is essential, since the bug tracking system is made to... track bugs. Every bug. If you discover something wrong, don't just fix it. Document it through bug tracking system. When later, a customer running a previous version of the software will report a bug which is an exact duplicate, you will be able to link it to your report. If you have nothing to link to, you'll waste your time (or your colleague) searching for the bug in previous revisions, then try to solve it, and finally find that the bug was already magically solved.

This also explains why freelancers must use both version control and bug tracking system: those two tools are not only for teams.


答:
I call the Structure a "Thick object". An alternative ("thin objects") is to stick to objects that are fully represented in a file, even if poor in high-level domain meaning

These are not exclusive.  You often need to do both.

You have physical format and logical layout issues separate from the problem domain.  Three layers.

objects are able to deserialize themselves from file ("pickle-like" in python parlance),

Doesn't work out well in the long run.  The class definition becomes cluttered with representation issues.

Python objects don't pickle themselves.  Pickling is handled separately.  Sometimes a class must provide codec hints to the pickle algorithm.

dumb data containers filled by stateless parser objects (one per file), or even by the database object itself.

"Stateless" parser objects don't always work out well.

Parser (or factory or builder) designs do work out well.  Just leave off "stateless."  Think of lexical scanning and parsing as separate from the physical, logical and final problem domain representations that may be required.

How should I perform proper deserialization in this case of "raw mapping"?

Physical Format classes may be necessary.  Often, these are already provided in a language library.  Don't reinvent the wheel.

Thin or thick objects ?

Not an exclusive choice.  You have logical layout and the proper domain-level classes independent of any physical representation.

Smart or dumb ?

Outside the problem domain, classes should be focused on representation.  I don't know of that makes them dumb or not.

Keep the concerns separate.

Physical format is for CSV, ZIP, XML, JSON, etc.

Logical layout handles variations in column names, data types, and structure.

Problem domain is the real objects you wanted to work with.


答:
There is no valid reason not to enter a defect into the defect tracking system. The only places where I have seen bug fixes applied without tracking is because the process was fundamentally broken. If this is the case, fix the process.

reasons for not entering are :

The process measures and punishes based on defect reporting -don't report, don't get punished. In this case leave the organization

The process is a burden - it takes too much effort and time to enter a defect and get to the point of fixing it.  The process should be changed to allow developers to fast track a lightweight bug through the triage/accept/fixed process.

Some devs are lazy/sloppy/hackers who don't care what the impact of the things they do on others might be. Recruit professional developers.

I'm a one man band, don;t see the point. Go work for a 2 man band and you will....


答:
This is an interesting thought (giving devs a slow machine may lead them to optimize more).

However, the solution is framed in a better way - put the response time in the requirements for programs, and have a low-end machine available for testing.

Also, if you have a really whiz-bang compiler/language, it might be able to devise different ways to generate code and pick the best one. That would only be helped by a faster computer.

Title: Does giving a developer a slower development machine result in faster/more efficient code?

Body:
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards


问:
How to go about bring up the topic of bad programming practices with colleague

Possible Duplicate:

  How do I approach a coworker about his or her code quality?

My development colleague is producing numerous blocks of code which I am a bit concerned doesn't really make for easy reading and potential issues in the future.  I've tried giving little tips along the way without blantantly saying what I think but his technique never seems to change.

I wouldn't normally be worried however we never identified any specific programming standards at the beginning of our project and it's now really starting to effect me a bit as I have to go through his code and try and debug it.

A small snippet of just a small part of the code is as such.

```<code>foreach(DistributionRecord record in _manager.Distributions)
{
    foreach (Engine.Model.DistributionModel.LossFromAtmosphericConditionsEnum NLossAt
                    in Enum.GetValues(typeof(Engine.Model.DistributionModel.LossFromAtmosphericStructureEnum)))
                    if (record.NlossAt.ContainsKey(NLossAt))
                        if (record.NlossAt[NLossAt].ContainsKey(DistributionModel.LossFromAtmosphericConditionsEnum.Atvolat))
                            _indirect[GetIndirectSourceEnumFromEnterpriseType(record)] += record.NlossAt[NLossAt][DistributionModel.LossFromAtmosphericConditionsEnum.Atvolat]
                                * _manager.Scenario.Management.EmissionFactors.EmissionFactorIndirectBackgroundVolatisation;

                foreach (Engine.Model.DistributionModel.LossOffEnum lossOff in Enum.GetValues(typeof(Engine.Model.DistributionModel.LossOffEnum)))
                    if (enterprise.NlossOff.ContainsKey(lossOff))
                        if (enterprise.NlossOff[lossOff].ContainsKey(DistributionModel.LossTypesEnum.lossleach))
                            _indirect[GetIndirectSourceEnumFromEnterpriseType(record)] += record.NlossOff[lossOff][DistributionModel.LossTypesEnum.lossleach][NutrientEnum.N].Value
                                * _manager.Scenario.Management.EmissionFactors.EmissionFactorN2OIndirectBackgroundLeach;
}
</code>```

I've talked to the boss and without blatantly saying it explained my concerns etc  I don't know what else to do.

Not sure if this is appropriate for this forum but any advice would be appreciated basically on how I can tackle this with my colleague.  Or perhaps I'm just being unrealistic and gotta get with the real world in that this is just how some people write code and it's ok?

答: Talk to your boss about institutuing a code review process. Then you can show him what the problems are officially and as a bonus, he will be expected to fix them before deploying. Of course your code will be reviewed and changes will be requested for it as well.</p>


答:
Silverlight will be slightly more "secure" as you are serving compiled code to the client rather than source to be interpreted on the client, but the code is still executed on the client.

Someone determined enough will be able to use reflection etc. to see inside your Silverlight XAP file if they so wish.

However, you will tie yourself up in knots worrying about this. Choose the best technology for your application and provide real value for people not to grab the code. This will depend on your application, but could include regular updates, on-line support, etc. Most people won't want to steal your code and those that are determined will do so anyway.

Title: Is HTML5 more secure to develop for than Silverlight?

Body:
I'm learning Silverlight, and I know that if I master it, I can apply the same concepts to WPF, which means I can do either web or desktop development pretty easily. But I've read articles and followed the discussion online, and I understand HTML5 is gaining traction for being cross-platform, and a lot of people seem to be moving to HTML5.

From my understanding, any HTML5 application would be built with HTML and JavaScript (or Flash). But is it secure? It seems like anyone can easily use their browser's "view source" option and grab your code. Is this something I should be worried about, or is there a way to protect against it?


问:
How do software engineers deploy applications?
Interested to know how people deploy software to their customers

I have the following requirements:

Customers on various OS's prob. linux and Windows

Can't release the source code

Ideally want option to develop GUIs not just cmd line stuff

Can't assume anything is pre-installed on customers machines

Would like to use a nice,high productivity language

I've used python for various stuff but am not sure how you could deploy it without releasing source code and without knowing your customers have python installed

I know you can make exes but its not really designed for that and your effectively compiling in the interpreter each time

Is there another similar high level language that can be properly compiled and distributed as a binary, possibly with a few supporting shared libs or something?

答:
Packaging

You would probably want to play to the normal expectations for each platform involved.

For example, Linux software is usually distributed through package managers, or as a package (RPM file, DEB file), or in the most basic form, an archive like tar, or a compressed tar. In the Linux world, though, since every distribution has very different environments/library versions, people usually ship source and then build for that specific platform to ensure the best compatibility.

Mac OSX software is typically distributed as a DMG or mpkg.

Windows software is usually distributed as an installer (either MSI or custom-exe), which can be built with software like Inno Setup, Wix, Nullsoft Installer, or if your users are savvier/you want to provide a portable app, you can provide a zip or a 7-zip self-executable.

Keeping your source hidden

Ignoring the group of users who would reverse engineer/decompile your code, you can provide software to your customers with Python. CPython compiles code to intermediate python byte code files, with the extension .pyc, and you can ship those to your users.

On Windows, you can use py2exe to create an executable. If you also don't want to assume your Linux users have python installed (which most would, but they might have versions you are incompatible with), then you can also use freeze, which allows you to ship python apps that don't rely on a pre-installed python.

More than just command line apps

If you take that Python information above, you can still build GUI apps with Python. You could use pyqt4, for example, which is a Python wrapper around the Qt4 framework.

In general you're going to be able to build GUIs, or use wrappers around other GUI libraries, in any language you'd realistically use.

High productivity

Well, this one is more vague - you use python, and python is high level. If the freeze/py2exe/compiled-python files work for you, then you don't really need to switch.

You could use a Java-based language, and build with something like Maven to create a JAR file which you could release to users. There is an (outdated) implementation of Python on Java (jython), a well-maintained Ruby implementation (JRuby), as well as other languages like Scala, Clojure, and Groovy. You can use Swing, SWT, or something like Jambi (Qt4 for Java) to build the UI for apps.

Of course you can fall back on using C or C++, and then use a build system like cmake to build and package your software (it supports creating archives of builds, as well as external tools like Inno), but how productive you are in C++ really depends on your comfort in using it and libraries and such that you need.

I'll just throw in an interesting choice here, for fun. Haskell (specifically Glasgow Haskell) can be compiled to native code, and can use C libraries through the FFI (foreign function interface). If you're a functional language wizard, it's a productive language.

How I did it

In the one job where I built software that required end users to install it, I wrote code in C++, and the building and packaging were handled for Windows and Red Hat Enterprise 4 and Red Hat Enterprise 5. We did not officially support other Linux distributions aside from special contract agreements, because of the time investment and the fact that no one used anything else to run this software.

The build system used cmake to build all the code, and for Windows builds, it would then package by calling out to Inno, which we scripted to copy all the libraries and build files necessary to ship an installer that would install a working copy of the software.

For Linux builds, the system used cmake's built in packaging mechanism and a file telling it how to package, where to place files, and such was created. The build system would package all the necessary libraries that the target Linux would not have by default (stuff like boost, Qt4, etc. was packaged by us), and so even if they ran it on a basic install, the libraries needed to run the code (aside from basic stuff like libc and libstdc++) were installed by us.


问:
Extensibility data model pattern
I was wondering how you'd be able to map the following criterias to common design patterns. I use PHP 5.3 and MySQL 5.5 and have my own mvc framework for my company but some parts could be better and here are the requirements:

(Take the concept of a catalog since it's the first app that would be affected in our application pool)

The controllers (products, clients and basket) all manage different information namely their own set of models. For example, the basket will create basket objects in memory, assign products to it, quantities, etc. Then it will save the basket to database and try the payment logic and save the payment associated to the basket.

My issue is that most of the time, our clients want to customize the different objects such as the client (add more coordinate fields or descriptive fields) or the product (add custom properties to the product). If my controller always refers to the class product but i want to extend it to create:

```<code>MyCompany_Models_Product
MyClient_Models_Product extends MyCompany_Models_Product
</code>```

How will i setup my system to support extension of classes and change the classes used by my different modules, controllers, views and other models. If i hardcode MyCompany_Models_Product as the class name in the controller and all other object, how would i go at creating an overridable system.

Is there any pattern i can go for that will leverage this problem?

答:
Don't do this through extension. You already have a sense for what a mess this can turn into. Compile-time extension can -very- easily lead to this kind of class explosion (You don't wanna extend Product once for every combination of extra properties the client needs). Instead, use runtime composition.

A few relevant questions:

Will these changes affect logic, or are they always (or even mostly) only be additional properties? If so, why not create a class called ProductProperty that has Key and Value properties? Create your Products through a factory that can not only instantiate the Product class, but can also check the database to see what additional fields the client has requested be on the Product. You may need to separately store this as metadata somewhere in the database. For every additional field your client has specified as needing, you can instantiate another ProductProperty and store them in some internal list of the Product instance.

You may also want to add some useful methods like Product.hasProperty, .getValue, etc, to make accessing - and maybe even iterating - these properties less of a hassle.

Title: Extensibility data model pattern


答:
I don't think there is a problem using subsystem because of small size alone. It is more a question of implementation/purpose: can the group of classes be considered a "component" on its own? Are they part of a bigger system? In that case it's a subsystem.

Cluster can sometimes be used as a generic term. The problem is that it can easily be confused with the "class cluster" design pattern, and data clusters.

Title: Proper terminology for a small set of tightly coupled classes?

Body:
What is the proper terminology for a small (2-4) set of tightly coupled classes? These classes can't work independently.

I was thinking system, but after googling for a bit, I've determined that the word is typically used to describe the software as a whole.

Then, I thought of subsystem, but I don't know if the term applies if the number of classes in the subsystem is small.

What do you guys think? This is for a presentation for a professor who wants me to provide definitions for everything.

Edit:

Essentially, I am describing various ways to architect game object systems, found in game engines. I'm using the term system as a way to include all the classes involved in the game object apparatus. Calling it a game object system feels right to me, but I'm not sure if it is the right terminology.

I don't view game objects as a layer, since it doesn't really work as a layer in a game engine. A module or package, to me, seem more suitable for a bunch of purely functional or stateless classes.

If I am not making sense, please let me know!


问:
Retexturing a model via API on the web
I'm looking at creating a site where a user could see our product and configure the options or look of it and see an image that represents that.

The way I'm doing it now is if you have Piece A selected and then you choose Texture X, I have an image on the filesystem that is A with X applied to it. I just swap out my default image with that specific one. One product has 8 areas, with 10-70 pieces per area, and about 200 textures for each piece. Programming the site was pretty simple but we are getting bogged down in rendering all these pieces/textures and entering them into the system.

What I would love to do is build a model and have some way to apply the textures via API and render it to the browser. I would even settle for exporting a flat image and pulling that into the browser.

Is that possible with something like SolidWorks, 3DSMax, or something else? If the rendering is too time intensive it would still help to batch create all my images and use them the way I am currently.

答: A number of 3d frameworks in Flash - Away3d especially - have some pretty robust APIs for loading models exported from high-end 3d programs as well as for applying Bitmap based textures to these models.</p>

Title: Retexturing a model via API on the web


问:
Tips for debugging with very little info?
I've inherited a project with a fairly large codebase, and the original developer rarely, if ever, replies to emails. There's a ton of different ways to do some things in it, and I don't know all of them. A lot of duplicated code along these paths (rather than functions included by, say, 5 pages that do relatively the same thing, it's code copied across 5 pages), and some subtle issues in the database (we've all heard of spaghetti code, but have you ever heard of a spaghetti database?)

All of this I can deal with most of the time no problem.

The issue is when a client finds a bug somewhere. They'll usually send a screenshot of the ending issue, and say, "Could you take a look at this?" while highlighting the specific thing on the page that's wrong, and sometimes what was expected. Very little more information is given, and trying to talk to them and get more (such as what they did to get the result) is like pulling teeth.

Basically, it boils down to this:

Large and complex code base I'm not 100% familiar with

Many many ways things can go wrong

Very little information on how a bug came to be

Does anybody have any tips, tricks, suggestions, etc. on how to debug this sort of thing?

答:
Start by writing unit tests.  Pick a class or a function and write a set of tests corresponding to how you think it should work.  If the tests fail, figure out why.  If it is a bug - fix it.  If your expectations turn out to be wrong, figure out what the thing actually does and modify the tests accordingly.

Once you have a decent set of working unit tests, you have a safety net for doing some refactoring to make the code cleaner.

Keep iterating until you understand the code base.

Needless to say, this is something you should do ahead of time, not in response to a bug report.


问:
Product classifying algorithm - text classification - C# - algorithm suggestions
Alright people. Finally with the help of stackoverflow community i have gathered 20 commercial product selling websites product pages with the following features

```<code>Product URL
Product Price
Product Name
Product Category
Product Page Title
Product Page Description
Product Page Keywords
</code>```

Now with using these features of the products i have to classify them. What does classification means ? Let me explain it.

Now as you can imagine every website lists the products in their own ways. There is not format. So lets say iphone 4 is being sold at 20 different websites with 20 different way. So what i need to achieve is grouping the these 20 iphone page at 20 different websites.
So when person query my website with iphone 4 word i will show that 20 results. Basically out of over 500.000 product urls i need to group every product. So lets say there are 15 gefore gtx 570 card out of these 500k urls so i need to group them as same product. You can imagine it as google products. But i am doing it at my own country which is Turkey and google does not have product search for Turkey.

In short with using the features above what algorithm would you suggest. I don't want to use any training techniques if possible. Everything automated.

I am using C# 4.0 WPF and data is stored at the MSSQL 2008 R2 database

答:
I would realize that features as Decorators from the Decorators pattern. Ie, each could envelope another decorator. So, the every real object will have features : FirstObject, FirstObject.envelopes, FirstObject.envelopes.envelopes, ... up to the last. You will have to make a function, that shows for any decorators all inner ones. And the function that will make from your DB such "MATRYOSHKA".

Any decorator will have its specific fields:

name of the feature

Value of the feature. A list of possible feature values should be set as a static list into every Decorator class.

Where it would be shown on what page at which format. This I would realize as a map of page types as keys and values=objects of a class Placement, will include place and format. These placements will do the real showing of the feature on the page.

Will you also analyze other pages? For here you could set also places where on the pages these features could be found. But this is very hard point.

Here you could put dependencies - what decorators could envelop by which.

Also here should be a mechanism for passing important information from the inner decorators to the outer ones. But that is the part of the design pattern standard.

The other variant - every object is a list of such features, only independent ones. But that is, IMHO, too dynamic construction for your task, and is harder to control.

This is the most primitive model.

As for more elaborated ones, you should take into account synonyms of the feature names. That means, that the list of possible feature values will change to list of lists.

The next step - some features could exist apart or together as one string. For example, GeForce or 590 or GeForce 590. For realization of this you should use Congregator instead of Decorator.

One more step - you should consider features that are represented by numbers (price, date). It is independent on the two previous steps.  Instead of lists of possible values, the decorator will have a range of possible values. The search pattern will be changed so, that the range setting will be possible.

The next independent step - ordering by features. You have all features ordered by including and all values are ordered by order in the lists of possible values. This is the natural order. But you could change the order.

So, two power instruments you should do: searcher UI and orderer UI. IMHO, try not to do the search or ordering for these objects by your code, use SQL instead. Objects should only represent them, used for input and output and setting search/ordering UI definition.

Of course, it could be elaborated further, but it would be better to realize the task step by step.


问:
How do I package a J2SE app for sale to a market of buying customers?
Currently, I enjoy my Java 101 class.  I have some ideas for apps that I'd like to make and with time and work I think the process of developing an application from the ground up will work out fine.  When I get my Java app(s) up and running - will it be easy to find a place where I can offer them for sale?

In the Enterprise labor marketplace, I see ads for developers with expertise with J2EE, WebSphere, Hibernate, Spring, etc.  As a Java newbie, I'm aware that I can forget about ever qualifying for those jobs.

An alternative for me might be to make something that I can build a micro-business with.  Is there a straightforward way of doing that?

答: You should note that most consumers don't care whether the app is written in Java, C# or whatever. Marketing it as "written in Java" will only work for some techies. Marketing it as "cross-platform, works in Windows, Mac and Linux" is much better.</p>


答: Fixing the bug right away is probably a bad idea. First, someone else might be working on the same fix, resulting in duplicated effort, and also, depending on the development methodology you're following, prioritizing what to work on next (fixing a bug or implementing a new feature) is more of a management decision then a development decision.</p>


答: In James Martin's Information Engineering Methodology, such a structure is denoted by "Business Area" - Business Areas divide the model space to include 'Entity Types' that are so related and serve the information needs of one or more areas of the business the system is built to support.


问:
What has research shown about the effectiveness of comments?
I have been arguing with a friend about the necessity of comments, and the efficiency of different comment styles. The argument ended quite fast, as we could not find any research - or essay - that support either claim.

Has any serious research been conducted regarding the efficiency of different commenting styles? If so, what has it shown? I'm mainly interested with:

Length (I think that comments longer than a tweet are never read)

Type (I strongly favor comments that are actual code samples, explaining how to call a method)

Location (As a separate line? at the end of the line?)

答:
The short answer is yes, there do exist published (in peer-reviewed journals and conferences) studies of various aspects of program comments.

Here are some examples:

Prechelt, et al (2001) determined that "Pattern Comment Lines" are effective when placed in programs in that maintenance tasks were completed faster with fewer errors.

Nurvitadhi, Wing Wah Leung and Cook (2003) determined that class comments are not useful for high-level understanding, however method comments helped with "low level program understanding".

A interesting read from the University of Montreal on comments in Java programs provides a good Related Work section that discusses some other research in this area.

None of these studies suggests that all comments in all situations are good. However they do provide some sound experimental evidence that comments are useful when done correctly.


问:
Is it legal to release GPL version project into FreeBSD?
I could not differentiate between FreeBSD and GPL liecense. Can anyone tell me the in what respect these two liecense are different.

Is it legal to use some source based on GPL license and release the new product as FreeBSD license?

In particular, I have following scence:

I would like to follow some of the implementation module of some implentation for my use. The implementation is standard algorithm implementation. So basically i am taking some reference to implement in my own way. I am not making use of verbatim copy, some module matches with the original one. The one which i am taking reference is in FreeGPL V3 license. The new product which i will release with FreeBSD license. Is it legal to do this or I should relase my product in FreeGPL license?

[EDIT]

Moreover, my case is, I am implementing some standard algorithm. Lets say here a data structure linked list. I think,whoever implements it, he/she will have same structure and similar kind of functions for search, delete and insert.Even the operations will be seen. I saw some code in internet and i got the influence of that of code my implementation which was so unavoidable. In this case how can a
programmer can claim that the particular code is his own original code?

答: The question isn't "how can a programmer can claim that the particular code is his own original code?', the question is "did you base your code on the GPL'ed code?".  If you did, then your stuck with releasing it under the GPL.


答: Come up with agreed on coding standards by committee (both of you and maybe your boss involved). Then the discussion on code written prior the issue isn't a problem. Also as HLGEM mention (and i upvoted) code reviews. But without the standard agreed on the reviews could end up causing some heated discussions.</p>

Title: How to go about bring up the topic of bad programming practices with colleague

Body:
Possible Duplicate:

  How do I approach a coworker about his or her code quality?

My development colleague is producing numerous blocks of code which I am a bit concerned doesn't really make for easy reading and potential issues in the future.  I've tried giving little tips along the way without blantantly saying what I think but his technique never seems to change.

I wouldn't normally be worried however we never identified any specific programming standards at the beginning of our project and it's now really starting to effect me a bit as I have to go through his code and try and debug it.

A small snippet of just a small part of the code is as such.

```<code>foreach(DistributionRecord record in _manager.Distributions)
{
    foreach (Engine.Model.DistributionModel.LossFromAtmosphericConditionsEnum NLossAt
                    in Enum.GetValues(typeof(Engine.Model.DistributionModel.LossFromAtmosphericStructureEnum)))
                    if (record.NlossAt.ContainsKey(NLossAt))
                        if (record.NlossAt[NLossAt].ContainsKey(DistributionModel.LossFromAtmosphericConditionsEnum.Atvolat))
                            _indirect[GetIndirectSourceEnumFromEnterpriseType(record)] += record.NlossAt[NLossAt][DistributionModel.LossFromAtmosphericConditionsEnum.Atvolat]
                                * _manager.Scenario.Management.EmissionFactors.EmissionFactorIndirectBackgroundVolatisation;

                foreach (Engine.Model.DistributionModel.LossOffEnum lossOff in Enum.GetValues(typeof(Engine.Model.DistributionModel.LossOffEnum)))
                    if (enterprise.NlossOff.ContainsKey(lossOff))
                        if (enterprise.NlossOff[lossOff].ContainsKey(DistributionModel.LossTypesEnum.lossleach))
                            _indirect[GetIndirectSourceEnumFromEnterpriseType(record)] += record.NlossOff[lossOff][DistributionModel.LossTypesEnum.lossleach][NutrientEnum.N].Value
                                * _manager.Scenario.Management.EmissionFactors.EmissionFactorN2OIndirectBackgroundLeach;
}
</code>```

I've talked to the boss and without blatantly saying it explained my concerns etc  I don't know what else to do.

Not sure if this is appropriate for this forum but any advice would be appreciated basically on how I can tackle this with my colleague.  Or perhaps I'm just being unrealistic and gotta get with the real world in that this is just how some people write code and it's ok?


答:
Of course you should enter it. Or at least report it to your QA people if that's your normal process.

Even if you do just fix the bug yourself, you'll want a record of the change so that it can then be tested to ensure that the fix actually works and that there hasn't been a regression. It's also possible a user might report the bug at some point, and if it's in the system and marked as fixed, your support people can tell them that it's already been addressed.


答:
I usually keep make a distinction between natural/canonical domain order and arbitrary order. If zipcode is a canonical order in this domain I would write the function as: customers.inNaturalOrder().

If you add a sortBy function you can have something like this: customers.sortBy(_.zipCode), which reads much better a

Minor nitpick, byZipCode reads like grouping to me, I would expect it to return a multimap of zipcode to customers.

Title: In Functional Programming, should domain-relevant simple functions (e.g., sorts) be reified?

Body:
In a functional application, should you wrap common higher-level functions in domain-meaningful names or should you leave them "bare"?

For instance, if you have a list of Addresses, and "sorted by zipcode" is a common domain-meaningful ordering (targeted mailers, etc.), is it preferable to write:

```<code>val sortedCustomers = customers.sort((a,b) => (a.zipCode compareTo b.zipCode) < 0)
</code>```

Or is it better to create a function sortedByZip(cs : Iterable[Customer]) : Seq[Customer]?

Creating the function has the advantage of being (minutely) more abstract, but has the disadvantage of being opaque, creating a name to remember, etc.

I'm asking in the context of a significant professional codebase, one that you intend to live for years, be as maintainable as possible, be "true" to the expectations of functional programmers, etc.


问:
Re-inventing system design for Scala
Many, many, moons ago, I did my masters in Object Orientated Software Engineering. I covered everything: project initiation, requirements, analysis, design, architecture, development, etc, etc. My favourite IT book of all time was Developing Object Oriented Software, an Experience Based Approach (IBM-1996). A book created by a group of true experts of their time. It describes a work product centric approach to object oriented analysis, design and development methods.

I designed and developed and was happy and at the top of my game, but I started to feel a little dated: Agile movements became fashion of the day and re-branded some well known iterative and incremental approaches with new hip words. Suddenly inexperienced developers started frowning when I said "requirements" or "architecture" as if these things were superseded by magic.

Design and development lost it's fun and I was about to leave the whole IT industry behind me.

Then I discovered Scala. Oh, like soft rain on a dusty road. Everything just became clear, the air became sweet again and the little light of my hard-drive would flicker deep into the night, merrily keeping me company in my world of discovery.

I like system design. I'm an architect at heart, more than a programmer. I love analyzing, designing, thinking, arguing, improving - I just love simple, clean and crisp designs.

How do we design pure Scala solutions?

Surely conventional sequence diagrams, interaction diagrams, object diagrams, etc, could all be replaced or improved for the goodness of blending imperative and functional object orientated systems. Surely there is an opening for something totally different!

I'm not looking for bloated complexity - I'm looking for flexible simplicity. Much like Scala is actually simple and easy (albeit different), but can be extended to fit your requirement like a pair of Yoga pants. There must be a design system for this lovely language that will start simple, and can be extended to fit your requirements and your domain. Surely UML can not be it!

So how do we design pure Scala systems? Imagine for a moment, you have the luxury to design a complete system from scratch, and know that you will only be using Scala - How will your models look? What types of diagrams would you have to describe structure and behaviour? How would you model Options, matches, mixins, singleton Objects, etc. without being drawn into the complexity of extending existing modeling techniques rather than a fresh, light-weight, innovative tool-set.

Does such a design/process/solution exist, or is it time to invent one?

答:
How do we design pure Scala solutions?

I think you're taking the wrong angle with this question. Your overall design for solutions should not be tied to a particular language; rather, it should correspond to the problem at hand. The great thing about Scala is that it is flexible enough to not get in your way when it comes time to implement your design. Java, on the other hand, enforces some design decisions (primarily, the everything-is-a-class mentality) that will make it feel a bit clunky.

When designing, try to model state explicitly. Immutable data and explicit state lead to designs which are much easier to reason about. Most of the time, this will translate nicely into a functional programming solution, although occasionally you might find that it is more efficient or more straightforward to use mutation and an imperative style; Scala accommodates both quite nicely.

Another reason Scala is so great at getting out of your way is its ability to create DSLs that suit your needs. You can make your own little language that solves a certain problem the "normal" way, and then simply implement it in Scala.

In summary, my main point is that you shouldn't be trying to "design pure Scala solutions". You should design solutions in the most natural and understandable way possible, and it just so happens that Scala is an incredibly flexible tool that can help you implement those solutions in a variety of ways. When all you know about is a hammer, every problem starts to look like a nail, so be sure to explore the various approaches there are available to you. Don't try to close the design process to steps X, Y, and Z, lest you miss out on possibilities A through W.

OwnerDisplayName: JacobusR

Title: Re-inventing system design for Scala


问:
Terminology - Cache (Javascript)
I have watched a couple videos on JavaScript where the presenter mentioned "caching" a variable but I didn't see them do anything in the code that would "cache" it beyond normal assignments. When I think of cache I think of something stored in local memory in which case aren't all JavaScript variables cached by definition.

When you cache a variable in JavaScript what are you "doing" to it?

EDIT:
I have heard the term in several but the only one that comes to mind is Writing Modular JavaScript - Tutorial. Which I just watched last night. I didn't post it because you have to pay to view and I hate feeling liking I am plugging a pay service on StackExchange.

答:
From this tutorial on efficient javascript:

One of the best kept secrets to boosting script performance is to
  cache your objects. Often times, your script will repeatedly access a
  certain object, as in the following demonstration:

```<code><script type="text/javascript">
for (i=0;i<document.images.length;i++)
document.images[i].src="blank.gif"
</script>
</code>```

In the above, the object "document.images" is what's accessed multiple
  times. The code to realizing it is inefficient, since the browser must
  dynamically look up "document.images" twice during each loop (once to
  see if i<document.images, and the other, to access and change the
  image's src). If you have 10 images on the page, for example, that's
  20 calls to the Images object right there. Excessive calls to
  JavaScript objects can wear down the browser, not to mention your
  computer's memory.

The term "cache your object" means storing a repeatedly access object
  inside a user defined variable, and using that variable instead in
  subsequent references to the object. The performance improvement can
  be significant. Here's a modified version of the initial script using
  object caching:

```<code><script type="text/javascript">
var theimages=document.images
for (i=0;i<theimages.length;i++)
theimages[i].src="blank.gif"
</script>
</code>```

Not only is the number of times document.images[] is referenced cut in
  half with the above, but for each time it is referenced, the browser
  doesn't have to go through document.images first, but goes straight to
  its containing array.

Remember to use object caching when calling highly nested DHTML
  objects, like document.all.myobject, or document.layers.firstlayer
  etc.

and

some JavaScript objects are less forgiving on the browser than others.
  While recognizing exactly which isn't easy (and isn't the goal here),
  just becoming aware of this fact is important.

Take, for example, these two properties:

```<code>-object.innerText //IE only
-object.innerHTML
</code>```

Did you know that the second property demands multiple times the
  system resources to call than the first? If all you're changing is the
  textual content of a
 or  and in IE only, innerText would
  definitely be the more efficient choice. Another example are the CSS
  properties "display" and "visibility"; the former is significantly
  more expensive than the later.

With JavaScript object caching, the number of lookups is cutdown, since the object reference is held within the variable - potentially improving performance and memory usage.

ContentLicense: CC BY-SA 4.0

Title: Terminology - Cache (Javascript)

Body:
From this tutorial on efficient javascript:

One of the best kept secrets to boosting script performance is to
  cache your objects. Often times, your script will repeatedly access a
  certain object, as in the following demonstration:

<script type="text/javascript">
for (i=0;i<document.images.length;i++)
document.images[i].src="blank.gif"
</script>

In the above, the object "document.images" is what's accessed multiple
  times. The code to realizing it is inefficient, since the browser must
  dynamically look up "document.images" twice during each loop (once to
  see if i<document.images, and the other, to access and change the
  image's src). If you have 10 images on the page, for example, that's
  20 calls to the Images object right there. Excessive calls to
  JavaScript objects can wear down the browser, not to mention your
  computer's memory.

The term "cache your object" means storing a repeatedly access object
  inside a user defined variable, and using that variable instead in
  subsequent references to the object. The performance improvement can
  be significant. Here's a modified version of the initial script using
  object caching:

<script type="text/javascript">
var theimages=document.images
for (i=0;i<theimages.length;i++)
theimages[i].src="blank.gif"
</script>

Not only is the number of times document.images[] is referenced cut in
  half with the above, but for each time it is referenced, the browser
  doesn't have to go through document.images first, but goes straight to
  its containing array.

Remember to use object caching when calling highly nested DHTML
  objects, like document.all.myobject, or document.layers.firstlayer
  etc.

and

some JavaScript objects are less forgiving on the browser than others.
  While recognizing exactly which isn't easy (and isn't the goal here),
  just becoming aware of this fact is important.

Take, for example, these two properties:

-object.innerText //IE only
-object.innerHTML

Did you know that the second property demands multiple times the
  system resources to call than the first? If all you're changing is the
  textual content of a <div> or <span> and in IE only, innerText would
  definitely be the more efficient choice. Another example are the CSS
  properties "display" and "visibility"; the former is significantly
  more expensive than the later.

With JavaScript object caching, the number of lookups is cutdown, since the object reference is held within the variable - potentially improving performance and memory usage.


答:
The answers here can help you figure out which kinds of references to your data get garbage collected at which point, with more detailed discussion here and elsewhere on the web. </p>

<p>When you're looking to keep data in local memory in javascript, you'll want to make sure you store a reference to it that stays in scope for as long as it's required. This will require that you make some assignments at some point - sometimes using local variables ( ie: var x = cached value), though, more likely, you'll want to place things onto longer lived objects,ie: </p>

```<code>jQuery.extend(myObject, {
   dog_cacher: []
}

...

myObject.dog_cacher = ["brown dog", "spotted dog"]
</code>```

Title: Terminology - Cache (Javascript)

Body:
I have watched a couple videos on JavaScript where the presenter mentioned "caching" a variable but I didn't see them do anything in the code that would "cache" it beyond normal assignments. When I think of cache I think of something stored in local memory in which case aren't all JavaScript variables cached by definition.

When you cache a variable in JavaScript what are you "doing" to it?

EDIT:
I have heard the term in several but the only one that comes to mind is Writing Modular JavaScript - Tutorial. Which I just watched last night. I didn't post it because you have to pay to view and I hate feeling liking I am plugging a pay service on StackExchange.

Body:
The answers here can help you figure out which kinds of references to your data get garbage collected at which point, with more detailed discussion here and elsewhere on the web.

When you're looking to keep data in local memory in javascript, you'll want to make sure you store a reference to it that stays in scope for as long as it's required. This will require that you make some assignments at some point - sometimes using local variables ( ie: var x = cached value), though, more likely, you'll want to place things onto longer lived objects,ie:

jQuery.extend(myObject, {
   dog_cacher: []
}

...

myObject.dog_cacher = ["brown dog", "spotted dog"]


问:
git / other VCS - how often to commit?
I've been a programmer now for over 11 years, and am just starting to get into version control for real. The places I've worked at have never really used version control (one committed at the end of each day, the others simply haven't bothered).

I am not happy with the way that I've been taught to version control (programme.js, programme.js.bak, programme.js.bak.20110901 etc) and so have been teaching myself to use git.

I currently use it along with github to keep my .vimrc file current across 4 machines, but I'm never sure when I should consider a change a commit, and when it's just a change which should be included along with another commit. I have started to use it for javascript development too and find it awesomely useful :)

My question is: At what point do changes become a commit? As I said, the only company I've worked for who used version control did it at the end of the day - this doesn't seem sensible to me. I feel that they should be more atomic. But my question is how atomic?

Is a bug fix for a function enough for a commit? Should I fix three (unrelated) functions and commit them all at once? Should I commit after changing the condition in an if statement?

On personal projects, I commit after any change. I personally find that useful, but I don't know if it's bad practice or annoying.

How do you do it, how does the industry do it, and what are best practices?

(I'm a web developer so work on short projects - perhaps a month long)

答:
Small commits aren't exactly that bad when they are clearly about fixing specific things. It's understandable that revision history can get crowded but it can also provide interesting insights about development style of the project team. When new developer joins the project, it can be useful for him/her to read revision history list if the changes are described clearly enough.

Still, there are some guidelines that vary project by project. Some have set of tests that must be run successfully before code can be committed, others are configured to run tests automatically after committing (useful example of public Continuous Integration test service is Travis CI).

Answer will also vary by the type of version management system used in the project. Having mostly used DVCS type tools, I feel that it can be useful reminder for myself to make small commits as it also works as partial documentation. Too large amount of smaller commits can be confusing at first but according to research, most of the commits in Open Source projects are small. There might be variance in how internal development works but often it's the little things that start to annoy in tools and small changes often are enough to fix specific problems.

Some of possible reasons for keeping it small:

"You should try to split your changes into small logical steps, and commit each of them. They should be consistent, working independently of any later commits, pass the test suite, etc."

Have found useful alias for seeing list of git commits in console. lg has really helped to see changes faster and more clearly than various other commit list views:

```<code># Show history in short format with colors
alias lg="git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative"
</code>```

Title: git / other VCS - how often to commit?

Body:
Small commits aren't exactly that bad when they are clearly about fixing specific things. It's understandable that revision history can get crowded but it can also provide interesting insights about development style of the project team. When new developer joins the project, it can be useful for him/her to read revision history list if the changes are described clearly enough.

Still, there are some guidelines that vary project by project. Some have set of tests that must be run successfully before code can be committed, others are configured to run tests automatically after committing (useful example of public Continuous Integration test service is Travis CI).

Answer will also vary by the type of version management system used in the project. Having mostly used DVCS type tools, I feel that it can be useful reminder for myself to make small commits as it also works as partial documentation. Too large amount of smaller commits can be confusing at first but according to research, most of the commits in Open Source projects are small. There might be variance in how internal development works but often it's the little things that start to annoy in tools and small changes often are enough to fix specific problems.

Some of possible reasons for keeping it small:

"You should try to split your changes into small logical steps, and commit each of them. They should be consistent, working independently of any later commits, pass the test suite, etc."

Have found useful alias for seeing list of git commits in console. lg has really helped to see changes faster and more clearly than various other commit list views:

# Show history in short format with colors
alias lg="git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative"


问:
Maintaining Organization When Designing Software
I've been trying for years to come up with a good way to organize the massive amounts of notes and material I generate when designing, coding, and testing software. My desk is usually overflowing with tons of sheets of paper with notes scrawled all over them. I've usually got at least the following items spread out all over these sheets of paper:

To-Do lists

Required features

Bug Descriptions

Program flowcharts

All sorts of design documents and diagrams, ranging from function design to overall program architecture

Use cases

List of test cases to design

Design questions that need to be answered in certain parts of the program

I'm pretty good at coding, but haven't learned how to manage my projects yet, since I'm still a student in school. I want to learn these skills, however, because I know I'll need them in future jobs that require greater organization skills.

What techniques, programs, methodologies, etc. can I use to become better organized when designing software? If you suggest any programs, I would prefer free software, since I'm a poor college student. :) Thanks in advance!

答:
Oh boy is this a big topic.  Some general thoughts on where to begin...

1) Start with something to get things under control.  Don't worry about perfection, just start and tweak.

2) Excel is your friend.  It can do 80% of what you need with 20% if the work, and that 80% will be easy to keep internally integrated.

3) Traceability is a good starting point.  Everything you do shoul map to a benefit, requirement, design, set of code and test.  You can use different names and phases but the core idea is to track what you need to do through the whole chain of activities.

4) Track every commitment, issue and risk in an online list.

This will get you started.  If you have more specific questions, let me know.


答:
Others have responded that generally you want developers to have fast machines.  I agree.  Do not skip on RAM - you want as much in memory as you can - some build processes are very heavy on disk usage.

Things you might want to consider getting rid of is antivirus on build drives!  That only slows down and can be an extremely strong slowing down factor.

You may want to let the developes develop on Linux if possible.  The tools there are much better for all kinds of extra tasks  (just grep for something in a file, etc).  This also gets rid of the anti-virus.


答:
Take the bullet points in your question, and make a manilla folder for each one.

Put all of the manilla folders in one of those green hanging folders, and label the green folder with the project name.

That's it.

Title: Maintaining Organization When Designing Software

Body:
I've been trying for years to come up with a good way to organize the massive amounts of notes and material I generate when designing, coding, and testing software. My desk is usually overflowing with tons of sheets of paper with notes scrawled all over them. I've usually got at least the following items spread out all over these sheets of paper:

To-Do lists

Required features

Bug Descriptions

Program flowcharts

All sorts of design documents and diagrams, ranging from function design to overall program architecture

Use cases

List of test cases to design

Design questions that need to be answered in certain parts of the program

I'm pretty good at coding, but haven't learned how to manage my projects yet, since I'm still a student in school. I want to learn these skills, however, because I know I'll need them in future jobs that require greater organization skills.

What techniques, programs, methodologies, etc. can I use to become better organized when designing software? If you suggest any programs, I would prefer free software, since I'm a poor college student. :) Thanks in advance!


问:
How to get contributors assign copyright for copyright holder?
Let's say we have a company and we release our project under LGPL && GPLv3, as you know the only thing here is about contribution. People commit bug-fixes/features to the project, it's fine and we are GPL fans.

Basically company makes money by this project. So what about contributors ? I know they commit code and software get better and it is actual repay to them, But how we can get contributors assign copyright for copyright holder?

答:
Make it a condition of the code being included in the project, ideally as part of the software license.

There are a number of software licenses that do this; for example, in the Mozilla Public License:

Each Contributor hereby grants You a world-wide, royalty-free,
  non-exclusive license:

a.under intellectual property rights (other than patent or trademark)
  Licensable by such Contributor to use, reproduce, make available,
  modify, display, perform, distribute, and otherwise exploit its
  Contributions, either on an unmodified basis, with Modifications, or
  as part of a Larger Work; and

b.under Patent Claims of such Contributor to make, use, sell, offer
  for sale, have made, import, and otherwise transfer either its
  Contributions or its Contributor Version.

The GPL, in particular, requires that all contributions made to a GPL project be licensed under the terms of the GPL.  So you shouldn't have to do anything else, other than make it clear to the contributors that this is the arrangement.

If you believe that some contributors may insist on retaining some or all rights to their code, simply have them sign a statement that indicates they are assigning copyright to your company; specifically, that it is a work for hire.  Make it a condition of them getting paid for the code.  Note that, in most jurisdictions (at least in the United States), if they are employees, you should already own the code.

Disclaimer: I am not a lawyer.  Treat this information accordingly.


问:
Syntax for goto labels
In C, C++ and some dialects of BASIC, goto labels are declared with the syntax label:. I'm working on a language that uses name: type as the syntax for variable declarations, so I'd prefer if possible to use something a bit more distinctive for labels. I am or at some point was passingly familiar with many languages that use that syntax for variable declarations, but off the top of my head I can't recall a single one of them that doesn't ban goto (not looking to argue about whether that's a good or bad design decision, just noting it did take place in those cases), so I'm trying to figure out where to look for precedent on labels.

What other forms of syntax has been used for goto labels? Are there any criteria I might be overlooking in choosing one over another?

(I just remembered Ada is an exception. But it uses <>, which doesn't mix well with the use of those symbols as C-style shift operators.)

答:
I am not sure where I am getting this from, but somehoew @: feels natural to me.

But I also suspect the 'right' answer depends on what else is going on in your new language, syntax-wise.

Title: Syntax for goto labels

Body:
I am not sure where I am getting this from, but somehoew @<label>: feels natural to me.

But I also suspect the 'right' answer depends on what else is going on in your new language, syntax-wise.


问:
Do you need to meet personally to collaborate effectively?
If you are starting up a web, mobile, or standalone application, how well must you know the rest of your collaboration team? Would it be a bad idea to ever work with someone unless I've met him personally? Is it okay to sometimes accept small public contributions such as code snippets and artwork without meeting the contributor? Should I ever actively collaborate with people online that I have not met, as long as the person has a detailed profile and a good reputation.

If you do collaborate online, what tools do you to build teams and find contributors? If not, would you consider the idea if there was a safe medium? Any other input on the subject would be appreciated.

答:
Not necessarily.  It depends on the personalities of the people involved.

I've seen musicians actually write and perform compositions using Internet tools, never meeting in person.  Programmers have the magical ability of distributed source control, so face-to-face meetings are not required at all to achieve something great.

Concerns about the quality of code that people submit, or whether or not they're on-board with the project's mission and vibe, can be alleviated by allowing people read access to the repository, but requiring another person to check in their changes after reviewing them.  When a person develops a level of trust by submitting productive changes for a period of time, you can give them full access.  Many open-source projects work this way.

Nevertheless, it is a fact that face to face meetings provide a much richer channel of communication than email, or even talking on the phone, especially if you're trying to collaborate on big-picture ideas.  Webcams can substitute for much of this interaction, but not completely.

And if you plan on doing business dealings with this person where money changes hands, I would consider developing a business relationship face-to-face indispensable.


问:
Should developers enter bugs into the bug tracking system?
While developing (either features or bug fixes) I sometimes happen to discover bugs that are not directly related to what I'm working on.  What should I do in that situation.  Just fix it?  Try to remember to fix it later?  Write it down somewhere?  Or enter it into the bug tracking system?

I generally enter it into the bug tracking system and let the process play itself out (i.e. triaging, assigning, etc.).  However I have hardly ever seen another developer enter a bug.  (Why is that?)

答:
The decision is not clear cut, and involves tradeoffs.

(some) PROS

Bug tracking is essential for communication, especially on large teams. One of the best benefits of having multiple eyes on the code is the ability to detect problems earlier, and that benefit is lost if bugs are not logged or tracked as you are developing.

Often, bugs are most easily fixed while you are already in a part of the code, working to understand it.

Even on smaller teams, there is a lot of benefit to be had morale wise by being able to list bugs, and progress at fixing them - sometimes the morale benefit is crucial even on one man projects.

Accurate bug detection can be very difficult after the fact - seeing a bug in code can save a lot of later work playing detective, trying to figure out where the issue originally occurred.

It's good for your general development as a developer to pay attention to bugs as you see them, and get in the habit of improving/cleaning up/reading code critically

Logging bugs as you find them is, generally speaking, a good habit to have.

(some) CONS

Entering bugs into a bug tracking system can be onerous and time consuming, and can be really disruptive to development work - more often so when working in large teams. You may be expected to:

check if your entry is a duplicate before entering (this could even be implicit, it's discouraging to enter your bug into the queue only to have it closed)

provide repeatable test case(s) for your report

accept later interruptions with questions about bug details, to accept/verify a fix when written

think about unrelated information that is often collected in bug tracking systems, such as which product is likely most affected, the priority of the bug, etc...

Sometimes bug tracking is just not the most efficient use of your time.

These are two general principles which can be hard to balance - finding a good strategy is a bit of an art. In situations like these, I think it's best to adopt a flexible heuristic, that I tweak as required for a given project, team, work environment, and your general skills. My strategy usually follows a pattern like approximately as follows:

Always log issues as you see them throughout your day, somewhere. Maybe on a sticky, maybe in a file to the side. Maybe all you log is a file name and line number, maybe more. Don't let the problem interrupt your current line of thought too much.

Take time at the beginning of each new work-day, as part of your warm-up for work, to deal with the stickies. I take 10-15 minutes to go through my list of detected issues from the day before and do whichever of the following is quickest:

Fix the issue and commit it (probably for one liner fixes or typos). If you're not permitted to commit without a bug report, create a side-project for small commits. When enough fixes accumulate in the side project, take the few hours you need to document them and commit.

Log the issue in a bug tracking system (for obvious issues that take longer to fix, but without onerous overhead)

Log the issue in a "to look at when not busy" document (I usually add a "//TODO - this looks broken, fix it" type comment to the source). Regularly take a day (I try for once a month) to go through the list and log it as appropriate - feature request, bug report, discuss with manager, etc...

Over time, I've found all sorts of tweaks as useful. For example:

In more rigid environments, I might just offload the bug reporting work to the testing team - get a tester to meet with me for an hour every once in a while, hand them the list of issues, and get them to do the logging. In environments where logging tests is a big deal, usually the tester will be glad for the free boost to their productivity.

Some teams refuse to allow any fixes that don't have a customer bug report behind them. I'd keep a project full of fixes on the side, and instantly commit them when the relevant issue is reported by a client, for free brownie points.

Some teams require that the person "owning" a chunk of code be the one performing fixes. I'd treat the code "owner" like a testing lead and meet informally to hand off issues occasionally

I find that, generally, as you follow this type of strategy, more and more of your peers and other company members will start to respect your work, and commitment to quality. After enough time, you'll have the respect and authority required to optimize the entire process to your liking. Keep an eye out for such opportunities, and take them as appropriate.


答:
No.

You need to meet in person, and share some time together to build trust.

Once you have trust going on, you can stay 3 timezones apart and hardly even notice.

Title: Do you need to meet personally to collaborate effectively?

Body:
If you are starting up a web, mobile, or standalone application, how well must you know the rest of your collaboration team? Would it be a bad idea to ever work with someone unless I've met him personally? Is it okay to sometimes accept small public contributions such as code snippets and artwork without meeting the contributor? Should I ever actively collaborate with people online that I have not met, as long as the person has a detailed profile and a good reputation.

If you do collaborate online, what tools do you to build teams and find contributors? If not, would you consider the idea if there was a safe medium? Any other input on the subject would be appreciated.


问:
OpenUp/Basic In Practice
I have some confusion understanding the OpenUp/Basic process. It is described as an iterative process consisting of four phases:

Inception,

Elaboration,

Construction, and

Transition.

I am not clear if a single iteration consists of all these phases or if we make several iterations within a single phase and then move to next phase. In the later case, it seems to be impractical but in former case feasibility of project can not be identified.

Is there anyone who has experience implmenting it in the organisation?

答:
Open Up is a "modified" version of Rational Unified Process.[RUP][ R is for Rational].

It is customizable  software developemnet process [ Infact you should always customize it to your own needs...You should have AUP where A stands for Anergy :-) ]

At RUP,OpenUP [and probably in your AUP] there are  4 phases.Each phase cosist of "n" iterations. Each iteration ends with "executable" software. But there may exception for this at "Inception".

At Inception you basically check/investigate  business-technological feasibility of software...You ask yourself should we do this, and if we want to do can we able to do it? For some large projects in order to answer those questions you may have to "write some software"...But this is so rare case...

At Elaboration basically you take most risky-hard parts of the system and code it iteratively...So at the end of this phase you will had a "solid" architecture which is proven by most risky-hard part of the system features/requirements...You have "executable architecture"- not  architecture stay just on "document"...

Then comes Construction in which you code relatively lower risk parts iteratively...This takes more time than the other phases generally...

Then  Transition....bla bla bla....

Shortly

Each phase in RUP/OpenUP consiste of several[n] iterations...

Each iteration generally result with executable code..

At each iteration you basically do Requirement analysis-
Implementation- Test - and produce "small version" of system which
can be exceuted tested..

At each iteration you incerement software...add some feature-value

RUP is iterative and incremental software developement process...

To get more undestanding i advice you to read/watch those :

Kruchten, "What Is the Rational Unified Process?" Link

Kruchten, "A Software Development Process for a Team of One" Link

Larman,Kruchten,Bittner, "How to Fail with the Rational Unified Process"Link

IJI Consulting, "Why Iterate? Understanding the Essentials of
Iterative Development" Watch at Youtube

IJI Consulting, "Are you ready for Iterative Development" Watch at youtube

OwnerDisplayName: anergy

Title: OpenUp/Basic In Practice

OwnerDisplayName: Novalis


问:
Does giving a developer a slower development machine result in faster/more efficient code?
Suppose I give my developers a screaming fast machine.  WPF-based VS2010 loads very quickly.  The developer then creates a WPF or WPF/e application that runs fine on his box, but much slower in the real world.

This question has two parts...

1) If I give a developer a slower machine, does that mean that the resulting code may be faster or more efficient?

2) What can I do to give my developers a fast IDE experience, while giving 'typical' runtime experiences?

Update:

For the record, I'm preparing my even-handed response to management. This isn't my idea, and you folks are helping me correct the misguided requests of my client.  Thanks for giving me more ammunition, and references to where and when to approach this.  I've +1'ed valid use cases such as:

- specific server side programming optimizations

- test labs

- the possibly buying a better server instead of top of the line graphics cards

答: Nope - in fact it would result in more bugs because they won't do as much testing, and they won't use extra tools like profilers as much.  Give them the best machines you can afford (including graphics acceleration hardware if you're a game development or graphics shop), and have them test inside VMs.  The VM specs can be scaled up or down as needed.</p>


答:
In my opinion, collaboration will always be better in person. I've worked on distributed teams, I've worked with offshore teams, I've worked in teams that were all co-located except for one individual. In all cases, unquestionably, the teams where everyone was co-located had the best communication.

That being said, communication amongst a distributed team can still be more than Good Enough. I worked on two separate teams that were distributed -- on was multi-state, one was everyone within the same county. In both cases the teams worked quite well. It really depends on the individuals and the type of work they are doing.

So, do you need to meet personally? As always, that depends. You probably don't genuinely need it, but it sure helps.


答:
Programming is a complex work fundamentally. The bugs are complex. so I used to assess a bug by two factors:

How often such kind of bugs may appear again in future? Whether this estimate is accurate or not, keep estimating.

When such kind of bugs appear again, is it easy to understand? This is accurate when you analyze this bug and fix it.

I would classify a bug into one of the following types:

Likely appear again in future, and easy to understand

Likely appear again in future, but hard to understand

Rarely appear again in future, and easy to understand

Rarely appear again in future, but hard to understand

In case 1, a cookbook or FAQ is a good device for the team to fix such bugs in future.

In case 2, an elaborate and comprehensible record is the necessary for the team because it is a waste of effort if another programmer endures such bugs again. For example: memory leak.

In case 3, I think it is not a big deal that there is nothing left for record because you won't spend too much time to fix an easy bug. For example, a typo for id of element in HTML.

In case 4, such bugs create a dilemma. It needs some time to write an elaborate and comprehensible record to describe such bugs. But this record is rarely used in future. Without a record, however, appearing of such bugs would be a struggle again. For example, such bugs appear because of computer virus in somebody's computer.


问:
How to market yourself as a software developer?
I have noticed that this is a frequent issue among younglings from technical areas such as ours.

In the beginning of our careers we simply don't know how to sell ourselves to our employers, and random guy #57 (who is a programmer, but not as good as you - technically) ends up getting a raise or a promotion because he knows how to communicate and market himself better than you. Many have probably seen this happen in the past, and most certainly many more will in the future.

What kind of skill/ability (either technical, or of other nature) do you think is relevant to point out when doing a job interview or asking for a raise, besides listing all the programming languages and libraries you know?

答:
This is the 16th answer to this question, so I won't rehash. I will add one simple observation:

Be random guy #57 by investing in your communications skills. Join a Toastmasters club (or start one - even at work) and leverage it to grow your communication skills, confidence, and leadership.

Try www.toastmasters.org (or google) to learn more and find a club, but here's the gist:

regular meetings where you practice speaking

well defined goals to gradually enhance communication skills

gain insight thru candid, positive feedback (giving and receiving)

multiple scenarios such as prepared speeches vs off the cuff speaking

meet other like-minded people and have fun

inexpensive, but work may even pick up the tab