问:
Is Ruby on Rails supposed to have a steep learning curve or is it just me?
I'm a self-taught programmer. I've been learning RoR since October with varying intensity (sometimes all day, sometimes nothing for several weeks). Before that I knew only Java, but knew it pretty well. I've heard so much hype about RoR and how it's supposed to make you happy, productive, etc. So far it's only made me frustrated.  I learned it out of the Agile book, and I suspect part of the difficulty might have to do with my not knowing JavaScript and CSS, and having only a shaky grasp of databases and HTML. But apparently it took me much longer to complete the project in the Agile book than other people, and I still don't remember much of it. There are some things about Rails that I just can't seem to get, e.g. when to use symbols and when NOT to, or how dynamic methods are called.

Recently I was given a small Rails assignment where I'm asked to make a small change to the interface. It's taken me around 25 hours and although I've made some progress in understanding the code, I still have no idea how to proceed. I can't even ask Stack Overflow because there is so much code I'll have to provide to give context.

So my question is in the title: is RoR supposed to take a long time to learn or am I just slow? Can it be that I've been learning from the wrong book? My learning style is such that I either understand nothing or understand everything, if that makes sense.

答:
When you're learning Rails and your only background is Java, you're not just learning a new web framework. You're learning a new programming language as well, and one that is significantly different from Java.

It may help for you to learn Ruby first and then look at Rails and its conventions. Learning what Rails does and how it does it went a lot easier for me once I no longer had to struggle to understand Ruby and could read (and write) Rails code/templates.

I went through the Ruby on Rails Tutorial and found it very helpful. The tutorial book is free and there is a version for Rails 2.3 and 3.0. You might also find it helpful to read up on MVC (Model-View-Controller) and web development/page lifecycle in general.


问:
When to use event.initMouseEvent for simulating mouse clicks?
I wonder if there are benign use-cases for simulating mouse clicks using event.initMouseEvent. I found that it is used for creating pop-under ads in the following way:

```<code>        var e = document.createEvent('MouseEvents');
        e.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, true, false, false, true, 0, null);
        a.dispatchEvent(e);
</code>```

This code simulates a click on the opening browser window, to force the newly opened window beneath it. Evil.

I'm thinking of simply preventing all simulated clicks in my own browser via a browser extension, but I wonder if I might break useful websites and behavior in the process. Therefore I wonder what situations justify simulating mouse clicks, and if there are big sites that use it in non-evil ways.

答:
e.initMouseEvent is used by some libraries to simulate click events on mobile phones. This allows code compatiblity between click and touch events.

You can check examples in Ionic or Leaflet

ContentLicense: CC BY-SA 3.0


问:
How to change the state of a singleton in runtime
Consider I am going to write a simple file based logger AppLogger to be used in my apps, ideally it should be a singleton so I can call it via

```<code>public class AppLogger {
    public static String file = "..";

    public void logToFile() {
        // Write to file
    }

    public static log(String s) {
        AppLogger.getInstance().logToFile(s);
    }
}
</code>```

And to use it

```<code>AppLogger::log("This is a log statement");
</code>```

The problem is, what is the best time I should provide the value of file since it is a just a singleton?

Or how to refactor the above code (or skip using singleton) so I can customize the log file path? (Assume I don't need to write to multiple at the same time)

p.s. I know I can use library e.g. log4j, but consider it is just a design question, how to refactor the code above?

答:
Allowing the file to change anytime raises a lot of red flags, such as major synchronization hassles.

But, even worse, what happens if Thread A is merrily logging 4 lines of

```<code>64.242.88.10 - - [07/Mar/2004:16:05:49 -0800] INFO:blah
INFO: Opening some connection to foo.bar.com
INFO: Connection established with 123.45.67.8
ERROR: Connection refused by socket 5432, bad credentials
</code>```

and in between line 1 and 2 (or maybe in the middle of them depending on the granularity) Thread B calls setFile(someCompletelyDifferentFile)?  Even if you synchronize per-line writes, this will be a mess.

Your logger should be configured early, preferably at application startup, before anybody starts using it, and then not change files in midstream.

Body:
Allowing the file to change anytime raises a lot of red flags, such as major synchronization hassles.

But, even worse, what happens if Thread A is merrily logging 4 lines of

64.242.88.10 - - [07/Mar/2004:16:05:49 -0800] INFO:blah
INFO: Opening some connection to foo.bar.com
INFO: Connection established with 123.45.67.8
ERROR: Connection refused by socket 5432, bad credentials

and in between line 1 and 2 (or maybe in the middle of them depending on the granularity) Thread B calls setFile(someCompletelyDifferentFile)?  Even if you synchronize per-line writes, this will be a mess.

Your logger should be configured early, preferably at application startup, before anybody starts using it, and then not change files in midstream.


问:
Prevent product key from being used on multiple virtual machines
I have a software product. it will probably run on VMs that have no network connection at all.

I want the user to pay for each VM the user runs.

I thought to ask the user for some kind of hardware ID and provide him with serial that is unique for his machine.

But user can just copy the VM image and than have two machines running?

So I thought of having a security dongle. But how can I prevent user from running two VM's on the same machine both connected to the same dongle?

This should be only basic defense so that actual hacking will be required to breach the license and not only spinning one more VM.

答:
The security dongle is a good idea.

Your software can run handshakes every minute (or second) with the device. If the device fails to respond then your program terminates.

Your dongle, on the other hand, keeps an internal counter and gives out unique hashes every time a session request is made, and has an internal timer that maintains active sessions. Every time a continuation request is made the dongle tracks whether the hash returned matches the expected hash, and if it doesn't, then the continuation request is denied and the program is forced to terminate.

Now the continuation request response could be in the form of a mutating hash too to make emulation a little more difficult.


问:
Is this a valid implementation of the repository pattern?
I've been reading up about the repository pattern, with a view to implementing it in my own application. Almost all examples I've found on the internet use some kind of existing framework rather than showing how to implement it 'from scratch'. Here's my first thoughts of how I might implement it - I was wondering if anyone could advise me on whether this is correct?

I have two tables, named CONTAINERS and BITS. Each CONTAINER can contain any number of BITs. I represent them as two classes:

```<code>class Container{
    private $bits;
    private $id;
    //...and a property for each column in the table...

    public function __construct(){
        $this->bits = array();
    }

    public function addBit($bit){
        $this->bits[] = $bit;
    }

    //...getters and setters...
}

class Bit{
    //some properties, methods etc...
}
</code>```

Each class will have a property for each column in its respective table. I then have a couple of 'repositories' which handle things to do with saving/retrieving these objects from the database:

```<code>//repository to control saving/retrieving Containers from the database
class ContainerRepository{

    //inject the bit repository for use later
    public function __construct($bitRepo){
        $this->bitRepo = $bitRepo;
    }

    public function getById($id){
        //talk directly to Oracle here to all column data into the object

        //get all the bits in the container
        $bits = $this->bitRepo->getByContainerId($id);
        foreach($bits as $bit){
            $container->addBit($bit);
        }

        //return an instance of Container
    }

    public function persist($container){
      //talk directly to Oracle here to save it to the database
        //if its ID is NULL, create a new container in database, otherwise update the existing one

        //use BitRepository to save each of the Bits inside the Container
        $bitRepo = $this->bitRepo;
        foreach($container->bits as $bit){
            $bitRepo->persist($bit);
        }
    }
}

//repository to control saving/retrieving Bits from the database
class BitRepository{
    public function getById($id){}
    public function getByContainerId($containerId){}
    public function persist($bit){}
}
</code>```

Therefore, the code I would use to get an instance of Container from the database would be:

```<code>$bitRepo = new BitRepository();
$containerRepo = new ContainerRepository($bitRepo);
$container = $containerRepo->getById($id);
</code>```

Or to create a new one and save to the database:

```<code>$bitRepo = new BitRepository();
$containerRepo = new ContainerRepository($bitRepo);

$container = new Container();
$container->setSomeProperty(1);
$bit = new Bit();
$container->addBit($bit);
$containerRepo->persist($container);
</code>```

Can someone advise me as to whether I have implemented this pattern correctly? Thanks!

答:
The implementation looks correct for me.

The approach may not scale well, because:

You recreate an object every time in getById,

You loop through all the objects in persist, while maybe only one changed,

But doing premature optimization would be worse: if performance corresponds to your expectations right now, don't change anything.

Later, if performance becomes an issue, consider:

Implementing caching strategy (given that it will probably be outside the repository, as an additional layer between the repository and the code which uses the repository),

Using observer pattern to track the changes in the objects: this way, when persisting changes, you don't need to do extra work, and can update only the data which actually changed.


问:
When do you use float and when do you use double
Frequently, in my programming experience, I need to make a decision whether I should use float or double for my real numbers. Sometimes I go for float, sometimes I go for double, but really this feels more subjective. If I would be confronted to defend my decision, I would probably not give sound reasons.

When do you use float and when do you use double? Do you always use double, only when memory constraints are present you go for float? Or you always use float unless the precision requirement requires you to use double? Are there some substantial differences regarding the computational complexity of basic arithmetics between float and double? What are the pros and cons of using float or double? And have you even used long double?

答:
For real world problems the sampling threshold of your data is important when answering this question. Similarly, the noise floor is also important. If either is exceeded by your data type selection, no benefit will come from increasing precision.

Most real world samplers are limited to 24 bit DAC s. Suggesting that 32 bits of precision on real world calculations should be adequate where the significand is 24 bits of precision.

Double precision comes at the cost of 2x memory. Therefore limiting the use of doubles over floats could drastically cut the memory footprint/bandwidth of running applications.

ContentLicense: CC BY-SA 4.0


问:
Keep a programming language backwards compatible vs. fixing its flaws
First, some context (stuff that most of you know anyway):

Every popular programming language has a clear evolution, most of the time marked by its version: you have Java 5, 6, 7 etc., PHP 5.1, 5.2, 5.3 etc. Releasing a new version makes new APIs available, fixes bugs, adds new features, new frameworks etc. So all in all: it's good.

But what about the language's (or platform's) problems? If and when there's something wrong in a language, developers either avoid it (if they can) or they learn to live with it.

Now, the developers of those languages get a lot of feedback from the programmers that use them. So it kind of makes sense that, as time (and version numbers) goes by, the problems in those languages will slowly but surely go away. Well, not really. Why? Backwards compatibility, that's why. But why is this so? Read below for a more concrete situation.

The best way I can explain my question is to use PHP as an example:

PHP is loved, and hated by thousands of people. All languages have flaws, but apparently PHP is special. Check out this blog post. It has a very long list of so called flaws in PHP. Now, I'm not a PHP developer (not yet), but I read through all of it and I'm sure that a big chunk of that list are indeed real issues. (Not all of it, since it's potentially subjective).

Now, if I was one of the guys who actively develops PHP, I would surely want to fix those problems, one by one. However, if I do that, then code that relies on a particular behavior of the language will break if it runs on the new version. Summing it up in 2 words: backwards compatibility.

What I don't understand is: why should I keep PHP backwards compatible? If I release PHP version 8 with all those problems fixed, can't I just put a big warning on it saying: "Don't run old code on this version !"?

There is a thing called deprecation. We had it for years and it works. In the context of PHP: look at how these days people actively discourage the use of the mysql_* functions (and instead recommend mysqli_* and PDO). Deprecation works. We can use it. We should use it. If it works for functions, why shouldn't it work for entire languages?

Let's say I (the developer of PHP) do this:

Launch a new version of PHP (let's say 8) with all of those flaws fixed

New projects will start using that version, since it's much better, clearer, more secure etc.

However, in order not to abandon older versions of PHP, I keep releasing updates to it, fixing security issues, bugs etc. This makes sense for reasons that I'm not listing here. It's common practice: look for example at how Oracle kept updating version 5.1.x of MySQL, even though it mostly focused on version 5.5.x.

After about 3 or 4 years, I stop updating old versions of PHP and leave them to die. This is fine, since in those 3 or 4 years, most projects will have switched to PHP 8 anyway.

My question is: Do all these steps make sense? Would it be so hard to do? If it can be done, then why isn't it done?

Yes, the downside is that you break backwards compatibility. But isn't that a price worth paying ? As an upside, in 3 or 4 years you'll have a language that has 90 % of its problems fixed.... a language much more pleasant to work with. Its name will ensure its popularity.

EDIT: OK, so I didn't expressed myself correctly when I said that in 3 or 4 years people will move to the hypothetical PHP 8. What I meant was: in 3 or 4 years, people will use PHP 8 if they start a new project.

答:
There are a few different problems with breaking backwards compatibility. Some of the problems stem from the fact that most programming languages are also platforms (interpreters/runtimes), other problems stem from an assumption of human nature.

A. Code written in an older versions wouldn't get the benefit of new releases that improve performance, security, or features. You could mitigate this problem by supporting multiple major versions of the compiler/interpreter, but that is a huge resource drain (ie its expensive or takes a long time, and is a pain in the ass).

B. Code written for the newer versions may not be compatible with code written in older versions. You could work around this by having an interpreter/compiler that can handle multiple major versions of the language, but this is more of a pain in the ass than supporting separate interpreters/compilers (the workaround for A).

C. Major changes, if they happen too often/quickly also simply make the language harder to use, since you have more to learn and unlearn. Changes to a language might push people over the edge to switch to a new language, or might cause people to continue to use outdated versions of the language and just never switch to the new version (like has happened with python). Then again, the changes may also attract new users and excite old ones.

D. New documentation needs to be kept and maintained. Its always a rather confusing experience to look up things on google and find that you're reading the docs for a different version than you're currently using.

By and large, if you create a programming language where external modules don't have to care what version you're using, breaking backwards compatibility for the right reasons (to fix major flaws in the language) is almost definitely the right thing to do. Its likely that the major reason this isn't done is that programming language designers overestimate (to contradict someone else's answer) the costs of breaking compatibility, especially early on. The fact is, the problems of breaking compatibility can be worked around or powered through by users of that language. And this doesn't only hold for programming languages; this applies to APIs, user interfaces - really any interface in any situation.

Facebook annoys the hell out of people when it changes its UI, or its developer APIs. In the past, its made the platform difficult to work with. In some cases, APIs simply stopped working out of the blue. But people kept using it, and now the APIs and UIs are leaps and bounds better than they were 5 years ago. People will complain about change whether its good or bad for them, but that (complaining) is not a good reason to forgo that change. Unfortunately, programming language developers use this as a reason to keep the problems of their language intact.

So another couple reasons for languages not making breaking changes to improve themselves are:

E. Language developers think their users fear of change is a good reason to stagnate their language

F. Language developers kind of liked their language when they made it, and they probably think its just fine with its flaws.

G. Languages as they grow older usually cease to have a small core set of developers, and turn into more committee-built beasts. This means decisions about those languages are slow and often conservative and uncreative.

H. The last reason is that some breaking changes require significant re-evaluation of design decisions made for the interpreter/runtime. Sometimes improvements to the language simply require too much work to be feasible. I would guess this is a rarer problem than most tho.

Often, language designers aren't necessarily tool designers, and so they don't think of good solutions to this problem, or they don't execute them well. Here are some solutions I can think of to solving the breaking-changes problem:

Deprecate things well ahead of when they'll be removed.

Provide a good, standard converter tool. Python provided the 2to3 tool, but it wasn't well advertised, didn't come standard with python 3 as I recall, and didn't even work very well (I remember having to manually go through programs generated by 2to3 to fix issues it didn't fix). This converter tool could even be automatically run if your compiler/interpreter detects an older version. What could be easier?


问:
Are null references really a bad thing?
I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake".  But why?  Sure, they can cause NullReferenceExceptions, but so what?  Any element of the language can be a source of errors if used improperly.

And what's the alternative?  I suppose instead of saying this:

Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
```

<p>You could say this:</p>

<pre class="lang-cs prettyprint-override"><code>if (Customer.ExistsWithLastName("Goodman"))
{
    Customer c = Customer.GetByLastName("Goodman") // throws error if not found
    Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman.  How lame!"); }
</code>```

But how is that better?  Either way, if you forget to check that the customer exists, you get an exception.

I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive.  Is that all there is to it?

答:
The problem isn't so much null, it's that you can't specify a non-null reference type in a lot of modern languages.

For example, your code might look like

public void MakeCake(Egg egg, Flour flour, Milk milk)
{
    if (egg == null) { throw ... }
    if (flour == null) { throw ... }
    if (milk == null) { throw ... }

    egg.Crack();
    MixingBowl.Mix(egg, flour, milk);
    // etc
}

// inside Mixing bowl class
public void Mix(Egg egg, Flour flour, Milk milk)
{
    if (egg == null) { throw ... }
    if (flour == null) { throw ... }
    if (milk == null) { throw ... }

    //... etc
}
```

When class references get passed around, defensive programming encourages you to check all parameters for null again, even if you just checked them for null right beforehand, especially when building reusable units under test. The same reference could easily be checked for null 10 times across the codebase!

Wouldn't it be better if you could have a normal nullable type when you get the thing, deal with null then and there, then pass it as a non-nullable type to all your little helper functions and classes without checking for null all the time?

Thats the point of the Option solution - not to allow you to switch on error states, but to allow design of functions which implicitly cannot accept null arguments. Whether or not the "default" implementation of types are nullable or non-nullable is less important than the flexibility of having both tools available.

http://twistedoakstudios.com/blog/Post330_non-nullable-types-vs-c-fixing-the-billion-dollar-mistake

This is also listed as the #2 most voted feature for C# -> https://visualstudio.uservoice.com/forums/121579-visual-studio/category/30931-languages-c

Title: Are null references really a bad thing?

Body:
The problem isn't so much null, it's that you can't specify a non-null reference type in a lot of modern languages.

For example, your code might look like

public void MakeCake(Egg egg, Flour flour, Milk milk)
{
    if (egg == null) { throw ... }
    if (flour == null) { throw ... }
    if (milk == null) { throw ... }

    egg.Crack();
    MixingBowl.Mix(egg, flour, milk);
    // etc
}

// inside Mixing bowl class
public void Mix(Egg egg, Flour flour, Milk milk)
{
    if (egg == null) { throw ... }
    if (flour == null) { throw ... }
    if (milk == null) { throw ... }

    //... etc
}

When class references get passed around, defensive programming encourages you to check all parameters for null again, even if you just checked them for null right beforehand, especially when building reusable units under test. The same reference could easily be checked for null 10 times across the codebase!

Wouldn't it be better if you could have a normal nullable type when you get the thing, deal with null then and there, then pass it as a non-nullable type to all your little helper functions and classes without checking for null all the time?

Thats the point of the Option solution - not to allow you to switch on error states, but to allow design of functions which implicitly cannot accept null arguments. Whether or not the "default" implementation of types are nullable or non-nullable is less important than the flexibility of having both tools available.

http://twistedoakstudios.com/blog/Post330_non-nullable-types-vs-c-fixing-the-billion-dollar-mistake

This is also listed as the #2 most voted feature for C# -> https://visualstudio.uservoice.com/forums/121579-visual-studio/category/30931-languages-c


答:
From your question, it's obvious that it is not only Rails you are trying to learn, but, at the same time you have to grasp concepts of web development, as well as databases and SQL. It's a huge task so please be patient.

On the other hand, with Rails you have no choice - you have to learn all three: M, V and C from MVC, all at the same time, but that would be the case with any MVC framework around, with Rails being among easiest, I'd say.

What you could do instead is to start with some simpler framework, such as Sinatra, until you get comfortable with basic concepts of Ruby and HTTP, and then slowly progress further towards richer presentation (views and CSS) and database-based models.

Title: Is Ruby on Rails supposed to have a steep learning curve or is it just me?

Body:
I'm a self-taught programmer. I've been learning RoR since October with varying intensity (sometimes all day, sometimes nothing for several weeks). Before that I knew only Java, but knew it pretty well. I've heard so much hype about RoR and how it's supposed to make you happy, productive, etc. So far it's only made me frustrated.  I learned it out of the Agile book, and I suspect part of the difficulty might have to do with my not knowing JavaScript and CSS, and having only a shaky grasp of databases and HTML. But apparently it took me much longer to complete the project in the Agile book than other people, and I still don't remember much of it. There are some things about Rails that I just can't seem to get, e.g. when to use symbols and when NOT to, or how dynamic methods are called.

Recently I was given a small Rails assignment where I'm asked to make a small change to the interface. It's taken me around 25 hours and although I've made some progress in understanding the code, I still have no idea how to proceed. I can't even ask Stack Overflow because there is so much code I'll have to provide to give context.

So my question is in the title: is RoR supposed to take a long time to learn or am I just slow? Can it be that I've been learning from the wrong book? My learning style is such that I either understand nothing or understand everything, if that makes sense.


问:
When is type testing OK?
Assuming a language with some inherent type safety (e.g., not JavaScript):

Given a method that accepts a SuperType, we know that in most cases wherein we might be tempted to perform type testing to pick an action:

```<code>public void DoSomethingTo(SuperType o) {
  if (o isa SubTypeA) {
    o.doSomethingA()
  } else {
    o.doSomethingB();
  }
}
</code>```

We should usually, if not always, create a single, overridable method on the SuperType and do this:

```<code>public void DoSomethingTo(SuperType o) {
  o.doSomething();
}
</code>```

... wherein each subtype is given its own doSomething() implementation. The rest of our application can then be appropriately ignorant of whether any given SuperType is really a SubTypeA or a SubTypeB.

Wonderful.

But, we're still given is a-like operations in most, if not all, type-safe languages. And that suggests a potential need for explicit type testing.

So, in what situations, if any, should we or must we perform explicit type testing?

Forgive my absent mindedness or lack of creativity. I know I've done it before; but, it was honestly so long ago I can't remember if what I did was good! And in recent memory, I don't think I've encountered a need to test types outside my cowboy JavaScript.

答:
There is an example that comes up often in games developments, specifically in collision detection, that is difficult to deal with without the use of some form of type testing.

Assume that all game objects derive from a common base class GameObject.  Each object has a rigid body collision shape CollisionShape which may provide a common interface (to say query position, orientation, etc) but the actual collision shapes will all be concrete subclasses such as Sphere, Box, ConvexHull, etc. storing information specific to that type of geometric object (see here for a real example)

Now, to test for a collisions I need to write a function for each pair of collision shape types:

```<code>detectCollision(Sphere, Sphere)
detectCollision(Sphere, Box)
detectCollision(Sphere, ConvexHull)
detectCollision(Box, ConvexHull)
...
</code>```

that contain the specific math needed to perform an intersection of those two geometric types.

At each 'tick' of my game loop I need to check pairs of objects for collisions.  But I only have access to GameObjects and their corresponding CollisionShapes.  Clearly I need to know concrete types to know which collision detection function to call.  Not even double dispatch (which is logically no different to checking for the type anyway) can help here*.

In practice in this situation the physics engines I've seen (Bullet and Havok) rely on type testing of one form or another.

I'm not saying this is necessarily a good solution, it's just that it may be the best of a small number of possible solutions to this problem

* Technically it is possible to use double dispatch in a horrendous and complicated way that would require N(N+1)/2 combinations (where N is the number of shape types you have) and would only obfuscate what you're really doing which is simultaneously finding out the types of the two shapes so I don't consider this to be a realistic solution.

Title: When is type testing OK?

Body:
There is an example that comes up often in games developments, specifically in collision detection, that is difficult to deal with without the use of some form of type testing.

Assume that all game objects derive from a common base class GameObject.  Each object has a rigid body collision shape CollisionShape which may provide a common interface (to say query position, orientation, etc) but the actual collision shapes will all be concrete subclasses such as Sphere, Box, ConvexHull, etc. storing information specific to that type of geometric object (see here for a real example)

Now, to test for a collisions I need to write a function for each pair of collision shape types:

detectCollision(Sphere, Sphere)
detectCollision(Sphere, Box)
detectCollision(Sphere, ConvexHull)
detectCollision(Box, ConvexHull)
...

that contain the specific math needed to perform an intersection of those two geometric types.

At each 'tick' of my game loop I need to check pairs of objects for collisions.  But I only have access to GameObjects and their corresponding CollisionShapes.  Clearly I need to know concrete types to know which collision detection function to call.  Not even double dispatch (which is logically no different to checking for the type anyway) can help here*.

In practice in this situation the physics engines I've seen (Bullet and Havok) rely on type testing of one form or another.

I'm not saying this is necessarily a good solution, it's just that it may be the best of a small number of possible solutions to this problem

* Technically it is possible to use double dispatch in a horrendous and complicated way that would require N(N+1)/2 combinations (where N is the number of shape types you have) and would only obfuscate what you're really doing which is simultaneously finding out the types of the two shapes so I don't consider this to be a realistic solution.


问:
How do programmers handle several versions of a same program?
A lot of apps, for instance, have a free version and pro version. Do programmers, when a new update is released, remove lines of code that shouldn't be available in the free version? As for Visual Studio. Or demos. Or a lot of things actually.</p>

答:
How about compile time pre-processor directives?  define FREE (or whatever you want to call your flag) in your compiler settings on Visual Studio and some features would not be built into the code.

See http://www.dotnetperls.com/if-elif-endif

http://msdn.microsoft.com/en-us/library/ed8yd1ha.aspx


答: Nothing environment specific, but security-wise it would be smart to not include the entire architecture in the "Full Version," because "Free-Trials" tend to be easier to crack/reverse-engineer. </p>

Title: How do programmers handle several versions of a same program?

Body: A lot of apps, for instance, have a free version and pro version. Do programmers, when a new update is released, remove lines of code that shouldn't be available in the free version? As for Visual Studio. Or demos. Or a lot of things actually.</p>


问:
Does this factory method pattern example violate open-close?
In Head-First Design Patterns, they use a pizza shop example to demonstrate the factory method pattern.

```<code>public abstract class PizzaStore {
  public Pizza orderPizza(String type) {
    Pizza pizza;

    pizza = createPizza(type);

    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();

    return pizza;
  }

  abstract Pizza createPizza(String type)
}

public class NYPizzaStore extends PizzaStore {
  Pizza createPizza(String item) {
    if (item.equals("cheese") {
        return new NYStyleCheesePizza();
    } else if (item.equals("veggie")) {
        return new NYStyleVeggiePizza();
    } else if (item.equals("clam")) {
        return new NYStyleClamPizza();
    } else if (item.equals("pepperoni")) {
        return new NYStylePepperioniPizza();
    } else return null;
  }
}
</code>```

I don't understand how this pattern is not violating open-close. What if we require a beef Pizza, then we must edit the if statement in the NYPizzaStore class.

答:
Technically, it's a violation, but it's not the worst kind of violation, because it's limited to that one spot.  You need some way of adding a new type to the list, and this way is simple and relatively foolproof.

Keep in mind that most programming languages don't have a straightforward way of automatically calling a function when a program loads.  You have to do weird things with templates or reflection.  That means even if you have some sort of way to dynamically register new pizza types with this factory, there's still some point where main eventually calls the register function for the new pizza type, so you have to add it to some list somewhere.  The advantage of putting it in the factory is you aren't initializing any resources for this pizza type until you actually need it.

In practice, it's extremely difficult to write pure OCP code, and usually not worth it.  If you're only editing one function, and that function is clearly an initialization list or factory, you're doing pretty well.


问:
How should I design a wizard for generating requirements and documentation
I'm currently working in an industry where extensive documentation is required, but the apps I'm writing are all pretty much cookie cutter at a high level. What I'd like to do is build an app that asks a series of questions regarding business rules and marketing requirements to generate a requirements spec.

For example, there might be a question set that asks "Does the user need to enter their age?" and a follow-up question of "What is the minimum age requirement?" If the inputs are "yes" and "18", then this app will generate requirements that look something like this:

"The registration form shall include an age selector"
"The registration form shall throw an error if the selected age is less than 18"

Later on down the line, I'd like to extend this to do additional things like generate test cases and even code, but the idea is the same: generate some output based on rules determined by answering a set of questions.

Are there any patterns I could research to better design the architecture of such an application? Is this something that I should be modeling as a finite state machine?

答:
This is not fully baked, but you should get the idea.

Requirements Table:

```<code>RequirementID     PK
Question          String
Action            String
Artifact          String
Condition         String
Role              String
Template          String
</code>```

Example tuple:

```<code>Question          "What is the minimum age requirement"
Action            "display an error message"
Artifact          "the registration page"
Condition         "age is less than <$ answer>"
Role              "user"
</code>```

Responses Table:

```<code>ResponseID        PK
RequirementID     FK
ProjectID         FK
Answer            String
</code>```

Pseudocode

```<code>foreach(response in Responses)
{
    // Display template text with text substitution
}
</code>```

Sample Template text

```<code>The application shall <$ Action> on <$ Artifact> when <$ role> is <$ condition>
</code>```

Body:
This is not fully baked, but you should get the idea.

Requirements Table:

RequirementID     PK
Question          String
Action            String
Artifact          String
Condition         String
Role              String
Template          String

Example tuple:

Question          "What is the minimum age requirement"
Action            "display an error message"
Artifact          "the registration page"
Condition         "age is less than <$ answer>"
Role              "user"

Responses Table:

ResponseID        PK
RequirementID     FK
ProjectID         FK
Answer            String

Pseudocode

foreach(response in Responses)
{
    // Display template text with text substitution
}

Sample Template text

The application shall <$ Action> on <$ Artifact> when <$ role> is <$ condition>


问:
How to represent a graph with multiple edges allowed between nodes and edges that can selectively disappear
I'm trying to figure out what sort of data structure to use for modeling some hypothetical, idealized network usage.

In my scenario, a number of users who are hostile to each other are all trying to form networks of computers where all potential connections are known. The computers that one user needs to connect may not be the same as the ones another user needs to connect, though; user 1 might need to connect computers A, B and D while user 2 might need to connect computers B, C and E.

Image generated with the help of NCTM Graph Creator

I think the core of this is going to be an undirected cyclic graph, with nodes representing computers and edges representing Ethernet cables. However, due to the nature of the scenario, there are a few uncommon features that rule out adjacency lists and adjacency matrices (at least, without non-trivial modifications):

edges can become restricted-use; that is, if one user acquires a given network connection, no other user may use that connection

in the example, the green user cannot possibly connect to computer A, but the red user has connected B to E despite not having a direct link between them

in some cases, a given pair of nodes will be connected by more than one edge

in the example, there are two independent cables running from D to E, so the green and blue users were both able to connect those machines directly; however, red can no longer make such a connection

if two computers are connected by more than one cable, each user may own no more than one of those cables

I'll need to do several operations on this graph, such as:

determining whether any particular pair of computers is connected for a given user

identifying the optimal path for a given user to connect target computers

identifying the highest-latency computer connection for a given user (i.e. longest path without branching)

My first thought was to simply create a collection of all of the edges, but that's terrible for searching. The best thing I can think to do now is to modify an adjacency list so that each item in the list contains not only the edge length but also its cost and current owner. Is this a sensible approach? Assuming space is not a concern, would it be reasonable to create multiple copies of the graph (one for each user) rather than a single graph?

答:
What you need is called an "attributed graph".  In an attributed graph, information (attributes) are attached to the arcs.  A weighed graph one of the simplest attributed graphs.

To represent an attributed graph, you can use an adjacency list by adding extra columns or adjacency matrices by adding more information in each cell.  Most algorithms for non-attributed graphs will work if you filter the arcs, based on the attributes. Many algorithms have been developed for attributed graphs, so I won't describe them here.


问:
What to Return with Async CRUD methods
While there is a similar question focused on Java, I've been in debates with utilizing Task objects. What's the best way to handle returns on CRUD methods (and similar)?

Common returns we've seen over the years are:

Void (no return unless there is an exception)

Boolean (True on Success, False on Failure, exception on unhandled failure)

Int or GUID (Return the newly created objects Id, 0 or null on failure, exception on unhandled failure)

The updated Object (exception on failure)

Result Object (Object that houses the manipulated object's ID, Boolean or status field to with success or failure indicated, Exception information if there was one, etc)

The concern comes into play as we've started moving over to utilizing C# 5's Async functionality, and this brought the question up of how we should handle CRUD returns large-scale. In our systems we have a little of everything in regards to what we return, we want to make these returns standardized...

Now the question is what is the recommended standard? Is there even a recommended standard yet? (I realize we need to decide our standard, but typically we do so by looking at best practices, see if it makes sense for us and go from there, but here we're not finding much to work with)

答:
After a lot of searching around the net as much as I could here's the end results I've come up with based on my research.

Things to avoid

Avoid using void with async methods. Voids don't pass exceptions up to the calling method which can lead to hard to debug async code. (this can be mitigated, but is still discouraged)

Avoid using Booleans with Create/Insert Method. returning the key is just as effective if all you care about is if it worked or not, plus there are many times you'll need that key immediately after the Create/Insert

Things to Consider

For all CRUD methods (except read) using a "Result Object" or "Façade Object" can make sense depending on your structure. If you take advantage of the object for stuff like error handling it can be beneficial, if not it'll probably be just a waste of time and resources.

Create / Insert Methods returning the key field is preferable to bool or void.

Update Methods returning bool is preferable to key or void if the update is a separate method, if it's an upsert treat it like an insert.

Delete Methods returning bool is preferable to void, key is fine, but often doesn't mistake

Read is a given in it should return whatever data was requested.

Personal opinion

Only use Result or Façade objects if you're going to use them for stuff like error handling, otherwise.

Create / Insert / Upsert : key field

Update : Boolean

Delete : Boolean

Read : Requested Data

Title: What to Return with Async CRUD methods


问:
How to write a user story specific to tasks in this case
We have planned to take up an user story say

As a player I want to view the game map to know current standings of my team

The sprint is for two weeks. We will be able to complete only HTML in two weeks time, this user story will take 4-6 weeks to be completed as we have a shortage of content designing resources.

How can we change this user story so that HTML completion can be considered as a done for this user story and we need to take up the integration of this user story in the next sprint?

Is it possible to create two different user stories, one for HTML and other for integration, testing, bug fixing etc?

答:
I think your question hides a bigger problem: the lack of content designing people (please don't call people resources, it depersonalizes them) seems to indicate that your team is working in development silo's.

On a recent project I worked on the same happened. We had front enders, integrators and back enders.

I was a nightmare. Although front enders were constantly busy, the integrators were not, and the backenders didn't know what to finish first. It ended up in having 40 or more unfinished stories at one point in time with nothing finished at all (beside the problems in the team, we also had to wait endlessly for stuff to be finished by another party).

We had to estimate the completion of stories just to give the customer an indication of the progress. Your question reminded me of this. Yes, we could show mockups to the customer, but as long as he couldn't use them (finished, fully documented, tested and approved), they were of no value to him.

My advice to you: when the content designing people are starting the work on a story, let them pair program with some of the others. It might cost some time in the beginning but might definitely be worthwhile the effort on the long run. With 20% of the knowledge often 80% of the work can be done. It can get some pressure of the current content designers and create a better flow in the team.


问:
Is NAN suitable for communicating that an invalid parameter was involved in a calculation?
I am currently working on a numerical processing system that will be deployed in a performance-critical environment. It takes inputs in the form of numerical arrays (these use the eigen library, but for the purpose of this question that's perhaps immaterial), and performs some range of numerical computations (matrix products, concatenations, etc.) to produce outputs.

All arrays are allocated statically and their sizes are known at compile time. However, some of the inputs may be invalid. In these exceptional cases, we still want the code to be computed and we still want outputs not "polluted" by invalid values to be used.

To give an example, let's take the following trivial example (this is pseudo-code):

```<code>Matrix a = {1, 2, NAN, 4}; // this is the "input" matrix
Scalar b = 2;
Matrix output = b * a; // this results in {2, 4, NAN, 8}
</code>```

The idea here is that 2, 4 and 8 are usable values, but the NAN should signal to the recipient of the data that that entry was involved in an operation that involved an invalid value, and should be discarded (this will be detected via a std::isfinite(value) check before the value is used).

Is this a sound way of communicating and propagating unusable values, given that performance is critical and heap allocation is not an option (and neither are other resource-consuming constructs such as boost::optional or pointers)?

Are there better ways of doing this? At this point I'm quite happy with the current setup but I was hoping to get some fresh ideas or productive criticism of the current implementation.

答:
Sounds fine by me as long as you've got your floating point model fixed, and you have said NaN semantics.

IEEE 754 is sufficient in your case.

http://en.m.wikipedia.org/wiki/Single-precision_floating-point_format

https://stackoverflow.com/questions/5777484/how-to-check-if-c-compiler-uses-ieee-754-floating-point-standard


答:
This is a completely reasonable way to go. Note also that there are multiple bit masks that are interpreted as NaN. There are two main types of NaN: signalling (which can throw an exception when they are created, depending on your settings) and quiet (which never do). Even within quiet NaN's however, there are multiple bit masks that correspond to quiet NaN. If you want to get really into it, you can create your own NaN's that are distinct from the regular NaN's. For instance, you could use a specific bit pattern that would correspond to NA (which is a different concept from NaN).

As for your point about pollution. This gets much trickier. Generally, any mathematical operation involving NaN results in NaN. In other words, NaN is contagious. In some cases, this is what you want. In others, it's not. For instance, suppose you were asked for the mean of the vector you gave. Is it NaN, or 7/3? The scalar * vector product you gave, however, will work out exactly the way you want, and you don't need to do any std::isfinite check either. Just multiply the numbers and the NaN pops out automatically, so it's quite performant. If you want to get a mean of 7/3 however for your vector, you need to be more clever, because doing it naively will result in NaN. While I can't tell you how to do a fast implementation of this, numpy has one, and its open source, so you can look at that.

Title: Is NAN suitable for communicating that an invalid parameter was involved in a calculation?

Body:
I am currently working on a numerical processing system that will be deployed in a performance-critical environment. It takes inputs in the form of numerical arrays (these use the eigen library, but for the purpose of this question that's perhaps immaterial), and performs some range of numerical computations (matrix products, concatenations, etc.) to produce outputs.

All arrays are allocated statically and their sizes are known at compile time. However, some of the inputs may be invalid. In these exceptional cases, we still want the code to be computed and we still want outputs not "polluted" by invalid values to be used.

To give an example, let's take the following trivial example (this is pseudo-code):

```<code>Matrix a = {1, 2, NAN, 4}; // this is the "input" matrix
Scalar b = 2;
Matrix output = b * a; // this results in {2, 4, NAN, 8}
</code>```

The idea here is that 2, 4 and 8 are usable values, but the NAN should signal to the recipient of the data that that entry was involved in an operation that involved an invalid value, and should be discarded (this will be detected via a std::isfinite(value) check before the value is used).

Is this a sound way of communicating and propagating unusable values, given that performance is critical and heap allocation is not an option (and neither are other resource-consuming constructs such as boost::optional or pointers)?

Are there better ways of doing this? At this point I'm quite happy with the current setup but I was hoping to get some fresh ideas or productive criticism of the current implementation.


问:
How to avoid or minimise use of check/conditional statement in my scenario?
I have scenario, where I got stream and I need to check for some value. If I got any new value I have to store it in any of data structure.

It seems  very easy, I can place conditional statement if-else or can use contain method of set/map to check either received is new or not.

But the problem is checking will effect my application performance, in stream I will receive hundreds for value in second, if I start checking each and every value I received then for sure it effect performance.

Anybody can suggest me any mechanism or algorithm to solve my issue, either by bypassing checks or at least minimize them?

答:
The likelihood is that using a hashed key for your data structure will be fast enough. Computing a hash function is typically just a few lines of code, and the look-up of a hashed key is just a few more. I would hazard a guess that a well-written Java implementation could handle something more than 1 million values per second on typical desktop hardware.

So write a naive implementation using some convenient hashed lookup (dictionary/map),  paying attention to the hashing function. Then benchmark it. It will probably be fast enough, and if not you have several options to speed it up. Once you get beyond 10 million per second, you will have an interesting problem, but that's a different question.


答:
A security dongle can easily do what you want, as this is a commonplace requirement. The dongle gives out a sequence of values according to a predetermined pattern. Two copies of your software running consecutively will see two sequences, each valid. Two copies running concurrently will see sequence breaks, where accesses by one copy interrupt the sequence for the other. Talk to your dongle provider for details. That's what they charge money for.

Thinking somewhat laterally, you don't have to solve this problem right away as long as your software expires. Make sure it can only run for some weeks or months and that it needs to be re-activated and/or updated at intervals. It should be easy to ensure that only one copy per licence key can be updated, and that the user would have to then re-clone all VMs. As you learn more about whether you actually have a problem and what shape it is, you can update the software to take increasingly aggressive counter-measures.

It may never be needed. Customers who come to depend on your software but are not paying enough yet are just future sales prospects.

Title: Prevent product key from being used on multiple virtual machines

Body:
I have a software product. it will probably run on VMs that have no network connection at all.

I want the user to pay for each VM the user runs.

I thought to ask the user for some kind of hardware ID and provide him with serial that is unique for his machine.

But user can just copy the VM image and than have two machines running?

So I thought of having a security dongle. But how can I prevent user from running two VM's on the same machine both connected to the same dongle?

This should be only basic defense so that actual hacking will be required to breach the license and not only spinning one more VM.


问:
Models, collections...and then what? Processes?
I'm a LAMP-stack dev who's been more on the JavaScript side the last few years and really enjoying the Model + Collection approach to data entities that BackboneJS, etc. uses. It's helped me organize my code in such a way that it is extremely portable, keeping all my properties and methods in the scope (model, collection, etc.) in which they apply.

One thing that keeps bugging me though is how to organize the next level up, the 'process layer' as you might call it, that can potentially operate on instances of either models or collections or whatever else. Where should methods like find() (which returns a collection) and create() (which returns a model) reside? I know some people would put a create() in the Collection prototype, but while a collection operates on models I don't think it's exactly right to create them. And while a find() would return a collection I don't think it correct to have that action within the collection prototype itself (it should be a layer up).

Can anyone offer some examples of any patterns that employ some kind of OOP-friendly 'process' layer? I'm sorry if this is a fairly well-known discussion but I'm afraid I can't seem to find the terminology to search for.

答:
In Domain Driven Design (DDD) this kind of thing would be in a 'Repository'.  The terminology used is to "rehydrate object(s) from the database".

For creation of objects, use a 'Factory' object.


问:
Is there a known standard data structure which is a hash table that resolves collisions using a binary tree?
Is there a known standard data structure which is a hash table that resolves collisions using a binary tree?
If so what is the name of this data structure?
I imagine such a structure would be useful as it should reduce the worst case search time down to O(log(n)) compared to O(n) in a hash table, and the best case would still be O(1).</p>

答:
Knuth came up with the name "ordered hash table" for this bucket collision strategy, which can use any of the many log n search data structures. Most people are not aware of that and in practice I've seen only KyotoDB using it.
Most others switched from simple linked lists to open addressing schemes (double hashing, Cuckoo, Robin Hood) for better cache performance.

"Ordered hash tables", O Amble, D Knuth 1973
http://comjnl.oxfordjournals.org/content/17/2/135.full.pdf

You can use a balanced tree, a trie, or just a simple ordered array with binary search, since mostly the bucket size will be < 8. It mostly a cache issue, so you will not want to use many pointers for a tree.


问:
C++ Without Source Files
Bjarne Stroustrup mentions in his book "The C++ Programming Language, 4th Edition" that not all C++ implementations use files to store and compile code:

There are systems that do not store, compile, and present C++ programs
  to the programmer as sets of files.

(Chapter 15, page 419)

Later in the chapter, he reiterates that certain implementations do not use files but he does not give any examples.

How would such an environment function compared to a more common file-based environment?

答:
As Basile hints in a comment, there are other ways to store source code than in text files.

VisualAge had the option to store it in a DB/2 database (worked with it, but never looked at the database) for example.

Borland's C++ Builder stored some code in binary format (especially the code for the visual representation of screens) rather than text files. This does use files, just not text files.

And of course entire operating systems exist that don't use files for storage, like the old Tandem NonStop operating system which used an SQL database as its filesystem.

I can conceive of an embedded system that stores data directly in EEPROM registers rather than as files on some device that then get read into that memory as required.

There are probably other options out there.

Title: C++ Without Source Files


问:
Why are private variables described in the publicly accessible header file?
OK, so hopefully this is a subjective enough question for Programmers, but here goes.  I am continuously broadening my knowledge of languages and software engineering practices... and I've run into something that just makes no sense to me whatsoever.

In C++, class declarations include private: methods and parameters in the header file, which, theoretically, is what you pass to the user to include if you make them a lib.

In Objective-C, @interfaces do pretty much the same thing, forcing you to list your private members (at least, there's a way to get private methods in the implementation file).

From what I can tell, Java and C# allow you to provide an interface/protocol which can declare all the publicly accessible properties/methods and gives the coder the ability to hide all implementation details in the implementation file.

Why?  Encapsulation is one of the main principles of OOP, why do C++ and Obj-C lack this basic ability?  Is there some kind of best-practices work-around for Obj-C or C++ that hides all implementation?

Thanks,

答:
The question is whether the compiler needs to know how large an object is.  If so, then the compiler has to know about the private members in order to count them up.

In Java, there's primitive types and objects, and all the objects are allocated separately, and the variables containing them are really pointers.  Therefore, since a pointer is a fixed-size object, the compiler knows how big a thing a variable represents, without knowing the actual size of the pointed-to object.  The constructor handles all of that.

In C++, it's possible to have objects represented locally or on the heap.  Therefore, the compiler needs to know how big an object is, so that it can allocate a local variable or array.

Sometimes it's desirable to divide class functionality into a public interface and a private everything else, and that's where the PIMPL (Pointer to IMPLementation) technique comes in.  The class will have a pointer to a private implementation class, and the public class methods can call that.

ContentLicense: CC BY-SA 2.5


答:
This example is not a violation of the open-closed principle. You can continue adding new types of pizza by subclassing NYPizzaStore:

```<code>class UpmarketNYPizzaStore extends NYPizzaStore {
    Pizza createPizza(String type) {
        if (type.equals("beef")) {
            return new BeefPizza();
        }
        return super.createPizza(type);
    }
}
</code>```

Title: Does this factory method pattern example violate open-close?

Body:
In Head-First Design Patterns, they use a pizza shop example to demonstrate the factory method pattern.

```<code>public abstract class PizzaStore {
  public Pizza orderPizza(String type) {
    Pizza pizza;

    pizza = createPizza(type);

    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();

    return pizza;
  }

  abstract Pizza createPizza(String type)
}

public class NYPizzaStore extends PizzaStore {
  Pizza createPizza(String item) {
    if (item.equals("cheese") {
        return new NYStyleCheesePizza();
    } else if (item.equals("veggie")) {
        return new NYStyleVeggiePizza();
    } else if (item.equals("clam")) {
        return new NYStyleClamPizza();
    } else if (item.equals("pepperoni")) {
        return new NYStylePepperioniPizza();
    } else return null;
  }
}
</code>```

I don't understand how this pattern is not violating open-close. What if we require a beef Pizza, then we must edit the if statement in the NYPizzaStore class.

Body:
This example is not a violation of the open-closed principle. You can continue adding new types of pizza by subclassing NYPizzaStore:

class UpmarketNYPizzaStore extends NYPizzaStore {
    Pizza createPizza(String type) {
        if (type.equals("beef")) {
            return new BeefPizza();
        }
        return super.createPizza(type);
    }
}


问:
How to refactor a myriad of similar classes
I'm faced with similar classes A1, A2, ..., A100. Believe it or not but yeah, there are roughly hundred classes that almost look the same. None of these classes are unit tested (of course ;-) ). Each of theses classes is about 50 lines of code which is not too much by itself. Still this is way too much duplicated code.

I consider the following options:

Writing tests for A1, ..., A100. Then refactor by creating an
abstract base class AA.

Pro: I'm (near to totally) safe by the tests that nothing goes wrong.

Con: Much effort. Duplication of test code.

Writing tests for A1, A2. Abstracting the duplicated test code and using the abstraction to create the rest of the tests. Then create AA as in 1.

Pro: Less effort than in 1 but maintaining a similar degree of safety.

Con: I find generalized test code weird; it often seems ... incoherent (is this the right word?). Normally I prefer specialized test code for specialized classes. But that requires a good design which is my goal of this whole refactoring.

Writing AA first, testing it with mock classes. Then inheriting A1, ..., A100 successively.

Pro: Fastest way to eliminate duplicates.

Con: Most Ax classes look very much the same. But if not, there is the danger of changing the code by inheriting from AA.

Other options ...

At first I went for 3. because the Ax classes are really very similar to each other. But now I'm a bit unsure if this is the right way (from a unit testing enthusiast's perspective).

答:
It seems covering all classes with unit-tests produce a lot of duplicated code. I would add some analysis stage before start writing unit-tests. Probably, some classes have the idential implementation, it could be detected by some static code analyzer (like Simian of PMD Copy-paste detector). These classes could be removed and the code could be refactored using plain search-replace or simple regexp

After finishing that stage you can start cover with unit test classes which have really different implementation

OwnerDisplayName: TobiMcNamobi


问:
Requesting feedback on my OO design
I'm working on an application that creates music by itself. I'm seeking feedback for my OO design so far. This question will focus on one part of the program.

The application produces Tune objects, that are the final musical products. Tune is an abstract class with an abstract method play. It has two subclasses: SimpleTune and StructuredTune.

SimpleTune owns a Melody and a Progression (chord sequence). It's play implementation plays these two objects simultaneously. StructuredTune owns two Tune instances. It's own play plays the two Tunes one after the other according to a pattern (currently only ABAB).

Melody is an abstract class with an abstract play method. It has two subclasses: SimpleMelody and StructuredMelody.

SimpleMelody is composed of an array of notes. Invoking play on it plays these notes one after the other. StructuredMelody is composed of an array of Melody objects. Invoking play on it plays these Melodyies one after the other.

I think you're starting to see the pattern. Progression is also an abstract class with a play method and two subclasses: SimpleProgression and StructuredProgression, each composed differently and played differently.

SimpleProgression owns an array of chords and plays them sequentially. StructuredProgression owns an array of Progressions and it's play implementation plays them sequentially.

Every class has a corresponding Generator class. Tune, Melody and Progression are matched with corresponding abstract TuneGenerator, MelodyGenerator and ProgressionGenerator classes, each with an abstract generate method. For example MelodyGenerator defines an abstract Melody generate method.

Each of the generators has two subclasses, Simple and Structured. So for example MelodyGenerator has a subclasses SimpleMelodyGenerator, with an implementation of generate that returns a SimpleMelody.

(It's important to note that the generate methods encapsulate complex algorithms. They are more than mere factory method. For example SimpleProgressionGenerator.generate() implements an algorithm to compose a series of Chord objects, which are used to instantiate the returned SimpleProgression).

Every Structured generator uses another generator internally. It is a Simple generator be default, but in special cases may be a Structured generator.

Parts of this design are meant to allow the end-user through the GUI to choose what kind of music is to be created. For example the user can choose between a "simple tune" (SimpleTuneGenerator) and a "full tune" (StructuredTuneGenerator). Other parts of the system aren't subject to direct user-control.

My question regarding this design is rather specific:

When I look at my design, it looks like the design-equivalent of 'code duplication': 'class-duplication' or 'design-duplication'. You can clearly see what I'm referring to if you look at the above diagram.

My question is split into two:

Is my intuition correct? Is this duplication, or reoccuring pattern in the design, a bad thing?

If it is, how can I design this differently and more efficiently?

答:
It looks like you have seen (or reinvented) the "composite pattern" somewhere, and now you are throwing it at at all of your main objects (tunes, melodies, progression), without knowing if it is really needed or not ("just in case"). This approach has a high risk of overdesigning things. The current design will allow you to model tree-like hierarchies of tunes, melodies and progressions, for which the tree structure of each is completely independent of each other. Do you really need that for your application? Is it necessary to have a simple tune build up from a

tree-like hierarchy of melodies, and a second

independent tree-like hierarchy of progressions?

Or does combining a structured melody consisting of 3 simple melodies with another melody consisting of 2 simple melodies result in a structured melody of 5 melodies, where the original grouping does not matter any more afterwards? If the latter is the case, I would try to start just with a Tune class, holding a list of melodies and a list of progressions.

And why do you need a complete "tree of tunes"?

And even if you are convinced you need all those hierarchies, it is definitely not clear why the generator hierarchy needs to follow the composite pattern at all. I guess you will need at maximum one generator object of each, so why not create, for example, a MelodyGenerator class, with just one object instance, which will be used to produce many melody objects (which will be either of type SimpleMelody or StructuredMelody). So if you need a "generateSimpleMelody" and a "generateStructuredMelody" method, make it two methods of the generator class, don't introduce an own class whenever you need just to add another method. A complete tree like hierarchy of MelodyGenerator objects seems IMHO to be pretty useless.

Nonetheless, "form follows function", so I would actually try to implement a part of your application, starting with the most simple possible object model you can think of (Robert Harvey's suggestion sounds well, a Melody with an array of notes maybe enough for the first version of your application), and extend your model whenever your application needs to get a feature you cannot solve with simple collection classes.

Title: Requesting feedback on my OO design


问:
Project structure: where to put business logic
First of all, I'm not asking where does business logic belong. This has been asked before and most answers I've read agree in that it belongs in the model:

Where to put business logic in MVC design?

How much business logic should be allowed to exist in the controller layer?

How accurate is "Business logic should be in a service, not in a model"?

Why put the business logic in the model? What happens when I have multiple types of storage?

However people disagree in the way this logic should be distributed across classes. There seem to exist three major currents of thought:

Fat model with business logic inside entity classes.

Anemic model and business logic in "Service" classes.

It depends.

I find all of them problematic.

The first option is what most Fowlerites stick to. The problem with a fat model is that sometimes a business logic funtion is not only related to a class, and instead uses a bunch of other classes. If, for example, we are developing a web store, there should be a function that calcs an order's total. We could think of putting this function inside the Order class, but what actually happens is that the logic needs to use different classes, not only data contained in the Order class, but also in the User class, the Session class, and maybe the Tax class, Country class, or Giftcard, Payment, etc. Some of these classes could be composed inside the Order class, but some others not. Sorry if the example is not very good, but I hope you understand what I mean. Putting such a function inside the Order class would break the single responsibility principle, adding unnecesary dependences. The business logic would be scattered across entity classes, making it hard to find.

The second option is the one I usually follow, but after many projects I'm still in doubt about how to name the class or classes holding the business logic. In my company we usually develop apps with offline capabilities. The user is able to perform entire transactions offline, so all validation and business rules should be implemented in the client, and then there's usually a background thread that syncs with the server. So we usually have the following classes/packages in every project:

Data model (DTOs)

Data Access Layer (Persistence)

Web Services layer (Usually one class per WS, and one method per WS method).

Now for the business logic, what is the standard approach? A single class holding all the logic? Multiple classes? (if so, what criteria is used to distribute the logic across them?). And how should we name them? FooManager? FooService? (I know the last one is common, but in our case it is bad naming because the WS layer usually has classes named FooWebService).

The third option is probably the right one, but it is also devoid of any useful info.

To sum up:

I don't like the first approach, but I accept that I might have been unable to fully understand the Zen of it. So if you advocate for fat models as the only and universal solution you are welcome to post links explaining how to do it the right way.

I'd like to know what is the standard design and naming conventions for the second approach in OO languages. Class names and package structure, in particular. It would also be helpful too if you could include links to Open Source projects showing how it is done.

Thanks in advance.

答:
I think you got Fowler wrong, he is advocating 3, not 1 (see http://www.martinfowler.com/bliki/AnemicDomainModel.html). Note that he is not talking about "business logic inside entity classes", he is talking about "business logic inside domain classes". And Service objects are domain objects.

In your example above: if you need to calculate the orders total, why not create a service class "OrderTotalCalculator"? Name the class accordingly for its purpose (and not OrderService or OrderManager, which would actually hide the purpose).

You already mentioned one criteria by yourself for when to introduce such a service class, and when business logic can stick inside entities: when "a bunch of other classes" is involved, then placing the logic in a specific entity is probably not the best design. You also mentioned the single-responsibility principle, so let yourself guide by this.

However, this does not necessarily lead to option 2 - since to my experience there are typically enough business operations for which an entity can take the full responsibility for itself, without introducing an extra service class for every operation. This will typically lead to a lean (but not anemic) entity classes.

The third option is probably the right one, but it is also devoid of any useful info.

Yes, it is probably the right one, but what do you mean by "is devoid of any useful info"? Do you miss an instructions manual on this? Software development is a design process, not like working at an assembly line. So making the right design decisions is not always easy and needs a lot of experience. And naming things is actually one of the hardest tasks.


问:
Passing functions into other functions as parameters, bad practice?
We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.

Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.

It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?

答:
It isn't a problem.

It is a known technique. These are higher order functions (functions that take functions as parameters).

This kind of function is also a basic building block in functional programming and is used extensively in functional languages such as Haskell.

Such functions are not bad or good - if you have never encountered the notion and technique they can be difficult to grasp at first, but they can be very powerful and are a good tool to have in your toolbelt.


答:
As already said, it isn't bad practice. It is merely a way of decoupling and separating responsibility. For example, in OOP you would do something like this:

```<code>public void doSomethingGeneric(ISpecifier specifier) {
    //do generic stuff
    specifier.doSomethingSpecific();
    //do some other generic stuff
}
</code>```

The generic method is delegating a specific task - which it knows nothing about - to another object that implements an interface. The generic method only knows this interface. In your case, this interface would be a function to be called.

Title: Passing functions into other functions as parameters, bad practice?

Body:
We've been in the process of changing how our AS3 application talks to our back end and we're in the process of implementing a REST system to replace our old one.

Sadly the developer who started the work is now on long term sick leave and it's been handed over to me. I've been working with it for the past week or so now and I understand the system, but there's one thing that's been worrying me. There seems to be a lot of passing of functions into functions. For example our class that makes the call to our servers takes in a function that it will then call and pass an object to when the process is complete and errors have been handled etc.

It's giving me that "bad feeling" where I feel like it's horrible practice and I can think of some reasons why but I want some confirmation before I propose a re-work to system. I was wondering if anyone had any experience with this possible problem?

Body:
As already said, it isn't bad practice. It is merely a way of decoupling and separating responsibility. For example, in OOP you would do something like this:

public void doSomethingGeneric(ISpecifier specifier) {
    //do generic stuff
    specifier.doSomethingSpecific();
    //do some other generic stuff
}

The generic method is delegating a specific task - which it knows nothing about - to another object that implements an interface. The generic method only knows this interface. In your case, this interface would be a function to be called.


答:
I take "sets of files" in this context as meaning named files stored in a filesystem on some kind of random access storage, and I take "present to the programmer" to imply that this filesystem should make its directory information (filenames) visible to the user.

Early computers presented source code to the compiler in the form of cards, paper tape or magnetic tape. They did not unify devices into the file system, so while the device might have a name the data currently loaded into it did not.

Embedded systems may be provided with an on-board compiler and read source code through a port.

The C/C++ addresses files by name but source code that has been pre-processed can certainly be read in from a reader or other device, compiled and executed in situ. I'm aware of this being done with Forth, and other languages are quite possible.

There were systems in which source code was stored in a database. The Pick system is the first that comes to mind, but there were others. Individual "files" were represented as records in a table in a database. This is kind of a file system by another name, but could certainly work. Perhaps it could be used for an interactive learning envirnonment, but I'm not aware of one.

Title: C++ Without Source Files

Body:
Bjarne Stroustrup mentions in his book "The C++ Programming Language, 4th Edition" that not all C++ implementations use files to store and compile code:

There are systems that do not store, compile, and present C++ programs
  to the programmer as sets of files.

(Chapter 15, page 419)

Later in the chapter, he reiterates that certain implementations do not use files but he does not give any examples.

How would such an environment function compared to a more common file-based environment?


问:
Why is cleverness considered harmful in programming by some people?
I've noticed a lot of questions lately relating to different abstraction techniques, and answers saying basically that the techniques in question are "too clever." I would think that part of our jobs as programmers is to determine the best solutions to the problems we are given to solve, and cleverness is helpful in doing that.

So my question is: are the people who think certain abstraction techniques are too clever opposed to cleverness per se, or is there some other reason for the objection?

EDIT: This parser combinator is an example of what I would consider to be clever code. I downloaded this and looked it over for about half an hour. Then I stepped through the macro expansion on paper and saw the light. Now that I understand it, it seems much more elegant than the Haskell parser combinator.

答:
To quote Brian Kernighan:

“Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.”


问:
What are the pros and cons of Coffeescript?
Of course one big pro is the amount of syntactic sugar leading to shorter code in a lot of cases. On http://jashkenas.github.com/coffee-script/ there are impressive examples. On the other hand I have doubts that these examples represent code of complex real world applications. In my code for instance I never add functions to bare objects but rather to their prototypes. Moreover the prototype feature is hidden from the user, suggesting classical OOP rather than idiomatic Javascript.

The array comprehension example would look in my code probably like this:

```<code>cubes = $.map(list, math.cube); // which is 8 characters less using jQuery...
</code>```

答:
pros

they really optimized the common cases syntatically, in fact, CoffeeScript is one of, if not the most concise language that is "commonly" used
http://redmonk.com/dberkholz/2013/03/25/programming-languages-ranked-by-expressiveness/

hides the bad parts of JavaScript (auto-coercion ==, implicit globals, more traditional class system makes common things easier)

extremely easy to learn for Python/Ruby programmers

multi-line anonymous functions + whitespace syntax

cons

removal of var means you can't change an outer-scope variable within an inner scope without using an object, or `var fall_back_to_js;` hacks [why not another assignment statement ':=' which only reassigns a value so obj.naem := 5 typos easier to debug]

you gotta let every tool know about it, unless you want to debug JavaScript :(;  btw: you can debug CoffeeScript from Chrome by adding support for source maps;  yeoman(npm install yeoman) can help you write a gulp or grunt config file for CoffeeScript

no optional static typing (gotta wait for the next EcmaScript standard)

still need third-party libraries for a module system

syntax traps to be careful of: implicit returns, a b g o means a(b(g(o))), f p, b: 2, c:8 means f(p, {b: 2, c: 8}) rather than f(p, {b: 2}, {c: 8})

doesn't change the broken JavaScript number/type system


问:
Google is good or bad for programmer?
Recently I was being interviewed by a company and faced one question. The interviewer asked me a question and at that time I didn't know the answer but if I had been asked about just 4 months ago, I could have answered it.

The question was from new language that I learned just 4 months ago. But I just get overview of the language and just get started working on that. Whenever I face difficultly, I google it. That means we do not have to memorize the whole programming language book! So in that situation I felt that Google screwed my job!

Not talking subjectively, Is it good to google all the time?

答:
Google as a language reference is all good in my opinion. I don't consider memorizing every piece of syntax or name of framework utilities to be a significant part of being a good programmer.

Speaking about whole solutions found on Google - well, anyone who is interested in quality and improving themselves will take the search result as an opportunity to study and learn. I don't just copy & paste some big block of code from link #1. I look through 5 or 10 different ways of solving my problem. Understand them, find how they differ and why, figure out which part I don't need, see which parts makes sense to me and apply to my particular project.

Seeing other people's solutions is not just a boost in productivity, it's vital for my development of skills and experience.

That said, I find it refreshing when I sometimes need to open up notepad and write some chunks of code, without intellisense, syntax highlighting or any help from Google.

Title: Google is good or bad for programmer?


问:
Is this JS code a good way for defining class with private methods?
I was recently browsing a open source JavaScript project. The project is a straight port from another project in C language. It mostly use static methods, packed together in classes. Most classes are implemented using this pattern :

```<code>Foo = (function () {
    var privateField = "bar";
    var publicField = "bar";

    function publicMethod()
    {
        console.log('this is public');
    }

    function privateMethod()
    {
        console.log('this is private');
    }

    return {
        publicMethod : publicMethod,
        publicField : publicField
    };
})();
</code>```

This was the first time I saw private methods implemented that way. I perfectly understand how it works, using a anonymous method. Here is my question : is this pattern a good practice ? What are the actual limitations or caveats ? Usually i declare my JavaScript classes like that :

```<code>Foo = new function () {
    var privateField = "test";
    this.publicField = "test";

    this.publicMethod = function()
    {
        console.log('this method is public');
        privateMethod();
    }

    function privateMethod()
    {
        console.log('this method is private');
    }
};
</code>```

Other than syntax, is there any difference with the pattern show above ?

答:
The first form can be generalized like so:

```<code>A = (function() { return {}; })();
</code>```

It gives us an object A with no explicit constructor. The object identifies exclusively as Object and the default Object constructor is used. Creating another object from A's constructor yields an empty object:

```<code>var a_test = new A.constructor();
</code>```

a_test will be an empty object ({}).

The 2nd form can be generalized like so:

```<code>B = new function() { /* whatever */ }
</code>```

It gives an object B which is an instance of an anonymous function. It's constructor is defined, and we can create new instances like so:

```<code>var b_test = new B.constructor();
</code>```

In this case, b_test will be identical to our original B object, private members and all.

The first form prevents users from building replicas. The second form allows it.

Body:
The first form can be generalized like so:

A = (function() { return {}; })();

It gives us an object A with no explicit constructor. The object identifies exclusively as Object and the default Object constructor is used. Creating another object from A's constructor yields an empty object:

var a_test = new A.constructor();

a_test will be an empty object ({}).

The 2nd form can be generalized like so:

B = new function() { /* whatever */ }

It gives an object B which is an instance of an anonymous function. It's constructor is defined, and we can create new instances like so:

var b_test = new B.constructor();

In this case, b_test will be identical to our original B object, private members and all.

The first form prevents users from building replicas. The second form allows it.


问:
In a specification, should I describe what a product does (ideally) or what it should/must do?
I'm writting a German specification (I'm not German).

Differences may appear for this process in different cultures, especially in the terminology, but usually here's the idea:

The client writes his needs and wishes in a document, called a scope statement or requirements document.

The supplier tries to understand the actual need of the client (which might be different to what was written and to what the client meant to say and to what the client thinks he needs, etc.)

The supplier writes a specification for the product, which should fill the client's need.

The specification needs to be precise enough for the product to be made (ambiguity problems occur).

The client and the supplier can check whether they have understood each other, and discuss details of the product.

The client agrees with the specification (or at least its current iteration) and the supplier is ready to start the work.

(it may of course be expected of you to disagree with this process, but this is irrelevant to my problem):

I'm now somewhere around the last two steps and I've been criticized because I wrote what the product must do, and not what it will do ideally.

Usually along the lines of

The product must be able to perform task A

And I was expected to write

The product performs task A

This is a simple word play, but I feel saying what the product does, while the product isn't even on the way to be made yet, is wrong.
I would tend to consider a specification as a contract of what the product is expected to do (what it must do and how it should do it), and not what it does.

Said differently, I feel this is the specification and not the manual of the end product……

Should I say what the product must do or what it does?

答:
Everybody has there own style, and at the end of the day, it's best to "dance with the one what brung you", (do what the person that's paying you says to do).

Having said that, I feel that it's all a question of abstraction levels and audience.  Let's suppose this is a chip design.  The answer below will apply equally well to software with the specific examples changed to meet the vocabulary and context of the day.  OK, back to levels of abstraction.

You should use 'must' statements when specifying a constraint for the system designers and the verification/testing engineers.  Consequently, you might see the following in a specification:

The SRAM buffer will have a throughput of at least 8 Mbits per second,
  and must be implemented using 9 nm CMOS technology compatible with the
  TSMC fab.

Translated, the specification writer wrote about the portion of the design where the designer is expected to exercise his craft/creativity, (the throughput o the buffer), in more relaxed terms than those used for the fabrication process where there is no wiggle room.


答:
This flow of events is very similar to what I work with. However, there are differences in terminology that I think may be causing some issues.

What the customer provides isn't a requirements document. It's likely to be a vision document or a concept of operations (CONOPS). These documents could call out the major features of the system, but they are written from the perspective of the customer or user, though, and tend to not be as technical (although they could be if they are coming from a technical customer or user) or as unambiguous as a design engineer or quality assurance engineer need to carry out their work.

Often, these documents tend to describe the customer's goals for the system - how they intend to use it, what they want to accomplish, and so on, but in their business language, using business terminology and concepts. This type of content is likely to not be suitable to the engineers building and designing the system, so it needs to be transformed.

Engineers will take the customer's inputs of a vision document or CONOPS (what you're calling a requirements document) and create a requirements specification. This is a formal statements of the functional and non-functional requirements, the quality standards, any design constraints, and use cases in a way that can be understood by the rest of the design. implementation, and test team. Regardless of the structure and format of the customer's input, the requirements documented in the specification should have the characteristics of a good requirement:

Each requirement addresses one thing (cohesive)

Each requirement is fully stated in one location (complete)

There are no contradictions between requirements or between a requirement and some external document (consistent)

Each requirement does not contain conjunctions, such as "and" (atomic)

Each requirement can be linked to a business need of one or more stakeholders (traceable)

Each requirement is not obsolete (current)

Each requirement is clear, acronyms are defined, is objective, avoids negative statements (unambiguous)

Each requirement makes it clear as to its importance

The implementation of each requirement can be determined through inspection, demonstration, test, and/or analysis (verifiable)

This document is the requirements specification for the product. It states exactly what the product must be able to do, when it is finished. If you have optional requirements, then those are clearly identified as optional and state what the project should do or may do. This is where the idea of writing requirements as "shall" statements come from. Optional requirements would replace "shall" with "can" or "may", and the meaning of "shall", "can", and "may" should be defined in the document so that the designers, implementers, and testers know the relative importance of each requirement.

By defining exactly how the product must behave, you are essentially providing instructions for the designers, testers, and (to some extent) implementers. They are starting with a system that does not yet accomplish all of the things and are being told what the thing is going to do when it is done. The design and implementation can be compared (in various ways) to this specification to ensure that it fully complies with what the customer intends.

Title: In a specification, should I describe what a product does (ideally) or what it should/must do?

Body:
I'm writting a German specification (I'm not German).

Differences may appear for this process in different cultures, especially in the terminology, but usually here's the idea:

The client writes his needs and wishes in a document, called a scope statement or requirements document.

The supplier tries to understand the actual need of the client (which might be different to what was written and to what the client meant to say and to what the client thinks he needs, etc.)

The supplier writes a specification for the product, which should fill the client's need.

The specification needs to be precise enough for the product to be made (ambiguity problems occur).

The client and the supplier can check whether they have understood each other, and discuss details of the product.

The client agrees with the specification (or at least its current iteration) and the supplier is ready to start the work.

(it may of course be expected of you to disagree with this process, but this is irrelevant to my problem):

I'm now somewhere around the last two steps and I've been criticized because I wrote what the product must do, and not what it will do ideally.

Usually along the lines of

The product must be able to perform task A

And I was expected to write

The product performs task A

This is a simple word play, but I feel saying what the product does, while the product isn't even on the way to be made yet, is wrong.
I would tend to consider a specification as a contract of what the product is expected to do (what it must do and how it should do it), and not what it does.

Said differently, I feel this is the specification and not the manual of the end product……

Should I say what the product must do or what it does?


问:
What to do about "next piece syndrome"?
Inspired by this question:
What to do about "stopping point syndrome"?

I often find myself a half hour away from knocking-off time having just wrapped up a component of my work, and facing a "next piece" that is going to take more than half an hour. (That's happening right now, as a matter of fact. Hence my surfing stackexchange during business hours!)

What do you do? Launch into the new piece knowing you'll have to stop in the middle? Set it aside and twiddle your thumbs until the clock runs out?

答:
Start working on the next piece.

When it's time to wrap up, find a logical place to stop (the last line of code, perhaps), save your work, write a brief note reminding yourself where you are and what you need to do next, leave it on your keyboard and go home.

Title: What to do about "next piece syndrome"?