问:
method to allow me ability to freely modify my classes, but make them immutable to others?
I am creating the model part of an MVC architecture.  My one class will provide all the accesses to allow one to fetch system state.  I want most of this state to be immutable as it shouldn't be changed and I don't want anyone accessing my model to be able to break the state by making a foolish change.

However, The objects representing the state have a bit of a tree structure.  object A contains a set of B which contains a set of objects C which contain a set of Object D etc etc.  Due to the nature of how I have to fetch the data I can't build the structure from the bottom up; the bottom most 'chid object' will be generated after all the others are completed.  This is making it rather inconvenient to build the immutable objects in an intuitive manner, I want to add a set as my last phase of building but I can't if I already built immutable objects.

I know of three approaches, but not sure I like any.  One is a builder patern, but keeping track of all the builders for a complicated structure until I'm done seems like it could be very ugly.  Second is to have a sort of 'clone' method that builds a new immutable object by cloning the old but adding a newly provided set to it (what is this pattern called again?).  This gets ugly when I try adding the child most element to the set since I need to pretty much rebuild the entire tree with 'new' immutable objects to add one value.

The third, and so far easiest, solution is to just get rid of the tree structure and make them make a call to my model to get the data they want.  so instead of calling myObject.getChildren they call Model.getObjectChildren (myObject).  This one will work, but darn it I wanted the pretty tree structure for my immutable state.

Is there some other way to conveniently build up my state in a manner where my Model can freely modify the state while being built; but still have in immutable when it's finally published to the Controller?

ps. I'm running in java if that matters.

答:
I would use interfaces for this:

```<code>interface ReadOnlyA {
    public ReadOnlyB getB();
    ...
}

interface ReadOnlyB {
    ...
}

class A implements ReadOnlyA {
    private B b;
    public B getMutableB() {
        return b;
    }
    public ReadOnlyB getB() {
        return getMutableB();
    }
    public void setB(B newB) {
        b = newB;
    }
}
</code>```

Basically, one interface per class that implements only read-only methods, and returns only instances of the read-only interfaces for other objects; but you use objects of the actual (mutable) classes internally.  I believe this is similar to the idea of capabilities --- a reference to the interface is equivalent to a 'read' capability, but your internal references to the classes are 'write' (and 'write contained objects') capabilities.

Body:
I would use interfaces for this:

interface ReadOnlyA {
    public ReadOnlyB getB();
    ...
}

interface ReadOnlyB {
    ...
}

class A implements ReadOnlyA {
    private B b;
    public B getMutableB() {
        return b;
    }
    public ReadOnlyB getB() {
        return getMutableB();
    }
    public void setB(B newB) {
        b = newB;
    }
}

Basically, one interface per class that implements only read-only methods, and returns only instances of the read-only interfaces for other objects; but you use objects of the actual (mutable) classes internally.  I believe this is similar to the idea of capabilities --- a reference to the interface is equivalent to a 'read' capability, but your internal references to the classes are 'write' (and 'write contained objects') capabilities.


问:
In Java, would you sacrifice type safety for a nicer programming interface
When and why would you generally sacrifice typesafety for a nicer programming interface?

Let me give you an example: if you had the choice between two event aggregators, which one would you prefer and why?

Reflective Version:

```<code>SomeEvent.subscribe(instance, "nameOfAMethod"); //method called via reflection
SomeEvent.fire(arg1, arg2);  //the firing could actually even be statically typed
</code>```

Statically typed version:

```<code>EventSystem.getEvent(SomeEvent.class).subscribe(new EventHandler<Payload>() {
   public void eventOccurred(Object sender, Payload payload) {
       //event handler code here
   }
});

EventSystem.getEvent(SomeEvent.class).fireEvent(payload);
</code>```

Please note, that in Java, due to type erasure, you cannot implement a generic interface with different type parameters more than once and need to resort to anonymous or external classes for handlers.

Now the reflective event system has a nicer user interface, but you lose type safety. Which one would you prefer? Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

答:
I think your example does not really compare things at the same level of detail, whereas this would:

stringly typed version:

```<code>public void subscribeTo(Event event) {
     event.substribe(this, "handleEvent");
}
public void handleEvent(Object sender, Payload payload) {
    //do something
}
</code>```

statically typed version:

```<code>public void subscribeTo(Event event) {
    event.substribe(new EventHandler<Payload>() {
        public void eventOccurred(Object sender, Payload payload) {
            //do something
        }
    });
}
</code>```

So in essence the latter is not critically longer. But as others have pointed out, it is both faster and safer.

If you're really that worried about token count, you shouldn't be using Java to start with ;)

ContentLicense: CC BY-SA 3.0

Body:
I think your example does not really compare things at the same level of detail, whereas this would:

stringly typed version:

public void subscribeTo(Event event) {
     event.substribe(this, "handleEvent");
}
public void handleEvent(Object sender, Payload payload) {
    //do something
}

statically typed version:

public void subscribeTo(Event event) {
    event.substribe(new EventHandler<Payload>() {
        public void eventOccurred(Object sender, Payload payload) {
            //do something
        }
    });
}

So in essence the latter is not critically longer. But as others have pointed out, it is both faster and safer.

If you're really that worried about token count, you shouldn't be using Java to start with ;)


问:
How web-servers identify a client
I have seen on some sites which say ,for-example, multiple votes/views from same computer will be neglected/penalized etc. For-example liking a facebook page, or youtube video from same computer(different accounts) will not increase its worth(according to my knowledge).

How do these sites identify bogus votes? I just need a direction.

答:
Without requiring user accounts (I'm assuming that your use case precludes them), there's no foolproof method to identify end users. But some common methods include:

Cookies

Set a cookie on the client machine to identify the user.

Pros: Definitely unique per session

Cons: Easy to remove or prevent (even for people with limited technical knowledge), only apply to one browser, easy for a script to bypass

IP address

Use the user's IP address to identify the user.

Pros: Changes infrequently, works across browsers, requires technical knowledge to spoof or use a proxy server

Cons: Not necessarily unique: one IP address can easily apply to entire homes/buildings/offices behind a network, and for some ISPs end user IP addresses might be reassigned

Browser fingerprinting

Use all browser data passed to the server (not just user agent, but also OS, screen resolution, and a number of other things) to generate a unique browser fingerprint.

Pros: High probability of being unique, opaque to the end user (changing IP addresses or clearing cookies won't bypass it)

Cons: Probably too unique -- any change in browser condition (or browser) will change the fingerprint (though you can choose only a subset of supplied browser information to balance fingerprint volatility and uniqueness), can be bypassed by scripts

You can, of course, also use multiple methods. Which method you use really depends on your specific use case. For many cases, just a simple cookie will do. If you want some defense against scripts or other methods of bypassing, add an IP address rate limit. You can also attempt to gather as much information as possible and use some sort of heuristic algorithm to try to find people that are bypassing the system for uniqueness that you have in place.

But again, there's no foolproof way to do this.

Title: How web-servers identify a client


问:
Is what someone publishes on the Internet fair game when considering them for employment as a programmer?
(Originally posted on Stack Overflow but closed there and more relevant for here)

So we first interviewed a guy for a technical role and he was pretty good. Before the second interview we googled him and found his MySpace page which could, to put it mildly, be regarded as inappropriate.  Just to be clear there was no doubt that it was his page (name, photos, matching biographical information and so on).

The content was entirely personal and in no way related to his professional abilities or attitude.

Is it fair to consider this when thinking about whether to offer them a job?

In most situations my response would be what goes on in someone's private life is their own doing. However for anyone technical who professes (implicitly or explicitly) to understand the Internet and the possibilities it offers, is posting things in a way which can so obviously be discovered a significant error of judgement?

EDIT: Clarification - essentially it was a fairly graphic commentary on porn (but of, shall we say, a non-academic nature).  I'm actually more interested in the general concept than the specific incident as it's something we're likely to see more in the future as people put more and more of themselves on-line.

My concerns are not primarily about him and how he feels about such things (he's white, straight, male and about the last possible victim of discrimination on the planet in that sense), more how it reflects on the company that a very simple search (basically his name) returns these things and that clients may also do it.  We work in a relatively conservative industry.

答: This is really a question for your HR department. My personal opinion is that publishing something on the Internet is equivalent to publishing something in a book. However, that won't help you if you get sued for employment discrimination.</p>

ContentLicense: CC BY-SA 2.5


问:
License for free but restricted software sharing
I have built a JavaScript library that I'd like to release for free within my user community. However I want to keep it under control, and not allow my users to pass it on to others without my permission.

As far as I can tell, a MIT or GPL license won't work for that scenario. What licensing options do I have?

Background: I've had some bad experience in the past where my solutions were used in situations other than the intended purpose, and this triggered maintenance and security issues. I am more careful this time.

答:
You could give each of your users a personal, non-exclusive, non-transferable license to use your library, but only for specific purposes which you specify. You could add a clause that they lose the right to use your software, should they violate these terms.

Such license agreements are common in the world of proprietary software (and please don't believe that you software isn't proprietary when you have such restrictive license conditions).

The fact that you don't actually take any money doesn't matter.


答: For sharing code with our clients (for verification of statistical methods for example) we simply use non-disclosure agreements. Those come with a hefty fine attached, but are necessary to protect our work.</p>

Title: License for free but restricted software sharing

Body:
I have built a JavaScript library that I'd like to release for free within my user community. However I want to keep it under control, and not allow my users to pass it on to others without my permission.

As far as I can tell, a MIT or GPL license won't work for that scenario. What licensing options do I have?

Background: I've had some bad experience in the past where my solutions were used in situations other than the intended purpose, and this triggered maintenance and security issues. I am more careful this time.


问:
Understanding unit tests/TDD for ASP.NET webforms
I'm the lead programmer at a small software firm (currently 4 developers including myself), we develop bespoke ASP.NET WebForms applications for businesses. I joined there in 2010 just after graduation, so it was my first real job. After more senior programmers left, I was promoted to lead and we hired a bunch of junior devs for me to mentor.

My issue is that currently, we have a huge amount of work from delayed projects (some 2-3 years delayed) so our development is very rushed and testing is left to the very last minute, and our releases often go out with obvious bugs we should have picked up. This really brings down morale and gets everyone very stressed, including myself.

We have no testing framework at all, or barely even any organisation to what we're meant to be doing. We never use unit tests, and all testing is manual and very laborious. This sort of methodology is all I've been exposed to since becoming a programmer, but I'm fast learning that this is not how a software house should work.

I've been trying to familiarise myself with TDD and Unit testing, but it's all extremely foreign to me and I'm having a hard time visualising how we could actually use these in our applications. Most of the logic inside our apps are in the code behind for each page (something I am now pushing to get away from) and from what I've read this makes testing much more difficult.

Does anyone have any advice, or know of any good tutorials, that'll help us get up to scratch with TDD?

We have a lot of other issues, including not using SVN efficiently, having a very basic HelpDesk for our bugs and giving our team fairly vague specs. Again these are things that I want to learn myself, but I'm needing to spend a lot of time actually teaching myself all of this. So if anyone has any advice for this I'd appreciate it but our testing is the most crucial thing right now.

答:
I'm in a similar place, so I can't offer the best help, and I'm eager to see the other answers.

But I can enthusiastically recommend Roy Osherove's "The Art of Unit Testing." It's focused on .NET and will give you plenty of ideas for what you should be aiming for in Unit Testing.

From what I know so far, you are right to be pushing the code to central classes, and out of the code behind. I'm working towards a more centralized architecture with better separation of concerns, similar to that encouraged by MVC. (Maybe worth some time looking at MVC just to get familiar with the architecture. Won't hurt the resume either.)


答:
I actually implemented a strongly-typed event system similar to yours once (in C#). It was horribly over-engineered and horrible to use. By the time I had discovered how horrible it was, it had spread throughout my application like a virus. It took forever to refactor, and it felt good when it was gone.

Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

Like this?

```<code>applicationEvents.Foo.Subscribe(myHandler)
</code>```

Yes. Definitely yes. Why not? It's way more simple, easy to understand, and type safe to boot. Any new developer would have all the available events in one place and wouldn't have to go searching your source code to figure out what events are available and how to use them.

No sense in sacrificing type safety when you don't have to.

EDIT:

If I seem overly aggressive, I apologize. I don't mean to criticize your design, I am just lamenting my own mistake which I made in the past, and it's very similar to what you're doing. Just be careful not to overcomplicate things.

Title: In Java, would you sacrifice type safety for a nicer programming interface

Body:
When and why would you generally sacrifice typesafety for a nicer programming interface?

Let me give you an example: if you had the choice between two event aggregators, which one would you prefer and why?

Reflective Version:

```<code>SomeEvent.subscribe(instance, "nameOfAMethod"); //method called via reflection
SomeEvent.fire(arg1, arg2);  //the firing could actually even be statically typed
</code>```

Statically typed version:

```<code>EventSystem.getEvent(SomeEvent.class).subscribe(new EventHandler<Payload>() {
   public void eventOccurred(Object sender, Payload payload) {
       //event handler code here
   }
});

EventSystem.getEvent(SomeEvent.class).fireEvent(payload);
</code>```

Please note, that in Java, due to type erasure, you cannot implement a generic interface with different type parameters more than once and need to resort to anonymous or external classes for handlers.

Now the reflective event system has a nicer user interface, but you lose type safety. Which one would you prefer? Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

Body:
I actually implemented a strongly-typed event system similar to yours once (in C#). It was horribly over-engineered and horrible to use. By the time I had discovered how horrible it was, it had spread throughout my application like a virus. It took forever to refactor, and it felt good when it was gone.

Would you create empty event classes just for the sake of having a symbol, like Microsoft does it with PRISM in its event aggregator?

Like this?

applicationEvents.Foo.Subscribe(myHandler)

Yes. Definitely yes. Why not? It's way more simple, easy to understand, and type safe to boot. Any new developer would have all the available events in one place and wouldn't have to go searching your source code to figure out what events are available and how to use them.

No sense in sacrificing type safety when you don't have to.

EDIT:

If I seem overly aggressive, I apologize. I don't mean to criticize your design, I am just lamenting my own mistake which I made in the past, and it's very similar to what you're doing. Just be careful not to overcomplicate things.


答:
I am not 100% certain what those two examples are supposed to do, but I guess an alternative would be to use an enum. I imagine the number of allowed strings like "nameOfAMethod" is limited and you could put the anonymous class gory stuff in that enum.

```<code>enum Methods {
    NAME_OF_A_METHOD {
        EventHandler get(final Object instance) {
            return new EventHandler<Payload>() {
                public void eventOccurred(Object sender, Payload payload) {
                    //do something with instance
                }
            }
        }
    };

    abstract EventHandler get(Object instance);
}
</code>```

And your example could become:

```<code>EventSystem.getEvent(SomeEvent.class).subscribe(NAME_OF_A_METHOD.get(instance));
</code>```

Not sure if it is directly applicable to your use case but you get the idea.

Body:
I am not 100% certain what those two examples are supposed to do, but I guess an alternative would be to use an enum. I imagine the number of allowed strings like "nameOfAMethod" is limited and you could put the anonymous class gory stuff in that enum.

enum Methods {
    NAME_OF_A_METHOD {
        EventHandler get(final Object instance) {
            return new EventHandler<Payload>() {
                public void eventOccurred(Object sender, Payload payload) {
                    //do something with instance
                }
            }
        }
    };

    abstract EventHandler get(Object instance);
}

And your example could become:

EventSystem.getEvent(SomeEvent.class).subscribe(NAME_OF_A_METHOD.get(instance));

Not sure if it is directly applicable to your use case but you get the idea.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答: Maybe The Huawei Software Company's coding standard. They want you to declare all members public:))</p>


答:
First of all, you definitely shouldn't feel bad that you're having a hard time getting to grips with this. WebForms is not a framework that was ever designed with testability in mind, and it certainly doesn't do anything to make itself easy to test.

The first and most important thing has already been mentioned in Jamie F's answer - you need to ensure that as little code as possible is in the .aspx page's codebehinds, and as much as possible is in separate business logic classes. The code in the codebehinds should be just wiring up the ASP.NET controls to and fro, and very little else. That way, you can start to get some unit tests around existing business logic and develop new business logic using a TDD approach.

For the actual web interface, you're probably better off looking into some browser automation testing framework - WatiN and Selenium are two that leap to mind. How to take a TDD approach to browser automation testing, though, I do not know. These techniques are, to my mind, much better suited to setting up regression tests after development is finished.

Title: Understanding unit tests/TDD for ASP.NET webforms

Body:
I'm the lead programmer at a small software firm (currently 4 developers including myself), we develop bespoke ASP.NET WebForms applications for businesses. I joined there in 2010 just after graduation, so it was my first real job. After more senior programmers left, I was promoted to lead and we hired a bunch of junior devs for me to mentor.

My issue is that currently, we have a huge amount of work from delayed projects (some 2-3 years delayed) so our development is very rushed and testing is left to the very last minute, and our releases often go out with obvious bugs we should have picked up. This really brings down morale and gets everyone very stressed, including myself.

We have no testing framework at all, or barely even any organisation to what we're meant to be doing. We never use unit tests, and all testing is manual and very laborious. This sort of methodology is all I've been exposed to since becoming a programmer, but I'm fast learning that this is not how a software house should work.

I've been trying to familiarise myself with TDD and Unit testing, but it's all extremely foreign to me and I'm having a hard time visualising how we could actually use these in our applications. Most of the logic inside our apps are in the code behind for each page (something I am now pushing to get away from) and from what I've read this makes testing much more difficult.

Does anyone have any advice, or know of any good tutorials, that'll help us get up to scratch with TDD?

We have a lot of other issues, including not using SVN efficiently, having a very basic HelpDesk for our bugs and giving our team fairly vague specs. Again these are things that I want to learn myself, but I'm needing to spend a lot of time actually teaching myself all of this. So if anyone has any advice for this I'd appreciate it but our testing is the most crucial thing right now.


答:
TDD is a paradigm shift, and is a type of testing. It also sounds like you would benefit from some general unit testing too, and maybe a couple new "policies" to which your team will adhere too. Couple things before you set out on the journey, make sure your team is on board, if they're not, try to convince them with articles and demonstrations. Make sure you include them and get their feedback along the way.

TDD (Test Driven Development) is write the test first, then write the code to pass the tests. This has been proven to work well, and lots of people are behind it.. It's probably easier to start a project with this type of strategy than to implement it mid-way through without a supporting code structure. There are many resources available out there on this.

Then you have unit testing, which in your case, is probably good to implement sooner than later. This type of strategy will just help you test your code. you write your code, and then test it (Arrange / Act / Assert). Unit testing just makes sure if you give the proper input, you get the proper output. Visual Studio had a testing framework built in, and XUnit is also a nice and easy testing framework to get started with and easy to implement.

I would start making it a practice to start developing in separate assemblies which can be referenced from the codebehind. That will create re-usability and will start towards a nice "layered" approach. Try to use good long naming conventions, and try to keep your classes organized and tidy. That shouldn't get in the way too much of the existing development process either.

IMO, the next step would be to start identifying "behavioral groupings" out of the codebase and make interfaces out of them

Isolate common methods within your applications which all pertain to
a common idea.

Create a class which implements that interface, and copy (cut actually) in the
methods from the codebehind so that they implement that interface (then reference that assembly and replace the codebehind methods with your "new" ones)

Eventually, you can start making some cool moves with those
interfaces including easier testability (dependancy injection, IoC containers, etc..)

I think pulling out interfaces is a good place to start because it's pretty easy with an existing codebase and the benefits of doing it are pretty high. here's a good video which speaks to the subject (BDD?) Integration Tests Are A Scam.

Lastly, i would recommend the Team Foundation Service. Sounds like your team can get into the free version since you get 5 members free. This is going to help you and your team  moving in an organized development direction as well as give you Source Control and a lot of other cool features like bug tracking, a "Big Board" (which is really cool), and a plethora of other good management tools which are useful for developers.

I hope at least some of this helps.. GOOD LUCK!


答:
As others have written, web forms was not developed with testability in mind however you can make your life a lot easier by learning patterns such as MVC, MVP and MVVM. Web Forms in particular plays quite well with MVP.

Dino Esposito has a great article here on MSDN about using MVP with web forms. You can also look at ASP.NET MVC which was built from the ground up taking into account dependency injection, inversion of control, testing, etc.

You essentially need to ensure the cleanest separation of concerns. Try looking into Aspect Oriented Programming to formalise this. By enforcing a separation of concerns you make it far easier to unit test, do dependency injection, and all the things you need to do to make testing simple. I've used Spring in Java, and they have an AOP module which is also in Spring.NET, it might be worth having a look at.

My suggestions are as follows:

Componetize the application as much as possible.

Do not mix business logic with display logic in web forms

Look to a pattern such as MVP or MVVM for web forms

Consider moving to ASP.NET MVC if it fits within your business goals

Adopt dependency injection to decouple your application

Write unit tests to test your code

Use automation testing to test your interface

The reason I am suggesting MVP/MVVM is because these patterns will help to enforce a separation of your data model from your view and therefore help enforce a separation of concerns.

Good luck!


问:
Boolean-Integer Typecasting to Replace Conditional
When choosing a value based off of 2 boolean values in this format

```<code>var foo:int;

if (X){
    foo = 50;
} else if (Y){
    foo = -50;
} else {
    foo = 0;
}
</code>```

I discovered that I can condense this down by typecasting the boolean operations to integers,  and mathing it up a bit like so:

```<code>var foo:int;

foo = ( int (X) - int(!X && Y) ) * 50;
// int() typecasts a boolean argument to an int of 1 if true, 0 if false.
</code>```

Here are my questions:

Is this approach less resource intensive?

Is this approach readable to you?

Is assigning values in this way common?

If 1 is true then in your opinion, does the performance increase justify the less readable nature of this approach?

This situation arose in ActionScript 3.0, but I am interested in answers from all languages, and from a best practice perspective.

答:
Is this approach less resource intensive?

I wrote two simple bits of C and looked at the dissassembly of each.

```<code>#include <stdio.h>

int main(int argc, const char * argv[])
{
    char x = argv[1][0] == 't';
    char y = argv[1][1] == 't';
    int foo;

    if(x) {
        foo = 50;
    } else if (y) {
        foo = -50;
    } else {
        foo = 0;
    }

    printf("%d",foo);
    return 0;
}
</code>```

and

```<code>#include <stdio.h>

int main(int argc, const char * argv[])
{
    char x = argv[1][0] == 't';
    char y = argv[1][1] == 't';
    int foo = ( x - (!x && y) ) * 50;

    printf("%d",foo);
    return 0;
}
</code>```

Pardon my dissasemblines, I'm on a mac rather than a linux box and so I don't have easy access to gcc -S so I'm not going to paste them here.  When looking at the sequence of events in each that is the if statements or the expression:

This sequence in the first is:

cmpb je movl jmp cmpb je movl jmp movl jmp leaq movl movb

The same reigon in the second version is:

movsbl cmpb movl movb jne movsbl cmpl setne movb movb leaq andb movzbl movl subl imull movl movl movb

The first you can see the compare, jump equal, assign, jump to end, compare, jump equal, assign, jump to end, assign.  IN the second, there is a significant amount of operations being done.  One can see the andb, subl and imull doing arithmetic operators.

The first will do a small number of comparisons to constants and branches.  The second does a significant number of operations.

Is this approach readable to you?

The first is by far more readable and maintainable.  Even if the second was to produce more optimal code, I would still write the first as the fractions of a second that are saved in the code are lost many times over when someone comes back to maintain the code and goes WTF?!

Is assigning values in this way common?

No.  I have never seen it before this situation.

If 1 is true then in your opinion, does the performance increase
  justify the less readable nature of this approach?

As I mentioned, the maintainability of the code is paramount in any situation where someone else may ever have the joys of touching your code later.

As a perl programmer, I recognize the value of hubris:

Hurbis: Excessive pride, the sort of thing Zeus zaps you for. Also the quality
  that makes you write (and maintain) programs that other people won't
  want to say bad things about. Hence, the third great virtue of a
  programmer.

I know I would say bad things about a programmer that writes the second, so I'm not about to do so.

Body:
Is this approach less resource intensive?

I wrote two simple bits of C and looked at the dissassembly of each.

#include <stdio.h>

int main(int argc, const char * argv[])
{
    char x = argv[1][0] == 't';
    char y = argv[1][1] == 't';
    int foo;

    if(x) {
        foo = 50;
    } else if (y) {
        foo = -50;
    } else {
        foo = 0;
    }

    printf("%d",foo);
    return 0;
}

and

#include <stdio.h>

int main(int argc, const char * argv[])
{
    char x = argv[1][0] == 't';
    char y = argv[1][1] == 't';
    int foo = ( x - (!x && y) ) * 50;

    printf("%d",foo);
    return 0;
}

Pardon my dissasemblines, I'm on a mac rather than a linux box and so I don't have easy access to gcc -S so I'm not going to paste them here.  When looking at the sequence of events in each that is the if statements or the expression:

This sequence in the first is:

cmpb je movl jmp cmpb je movl jmp movl jmp leaq movl movb

The same reigon in the second version is:

movsbl cmpb movl movb jne movsbl cmpl setne movb movb leaq andb movzbl movl subl imull movl movl movb

The first you can see the compare, jump equal, assign, jump to end, compare, jump equal, assign, jump to end, assign.  IN the second, there is a significant amount of operations being done.  One can see the andb, subl and imull doing arithmetic operators.

The first will do a small number of comparisons to constants and branches.  The second does a significant number of operations.

Is this approach readable to you?

The first is by far more readable and maintainable.  Even if the second was to produce more optimal code, I would still write the first as the fractions of a second that are saved in the code are lost many times over when someone comes back to maintain the code and goes WTF?!

Is assigning values in this way common?

No.  I have never seen it before this situation.

If 1 is true then in your opinion, does the performance increase
  justify the less readable nature of this approach?

As I mentioned, the maintainability of the code is paramount in any situation where someone else may ever have the joys of touching your code later.

As a perl programmer, I recognize the value of hubris:

Hurbis: Excessive pride, the sort of thing Zeus zaps you for. Also the quality
  that makes you write (and maintain) programs that other people won't
  want to say bad things about. Hence, the third great virtue of a
  programmer.

I know I would say bad things about a programmer that writes the second, so I'm not about to do so.


问:
How do you keep from running into the same problems over and over?
I keep running into the same problems.  The problem is irrelevant, but the fact that I keep running into is completely frustrating.

The problem only happens once every, 3-6 months or so as I stub out a new iteration of the project.  I keep a journal every time, but I spend at least a day or two each iteration trying to get the issue resolved.

How do you guys keep from making the same mistakes over and over?

I've tried a journal but it apparently doesn't work for me.

[Edit]

A few more details about the issue:  Each time I make a new project to hold the files, I import a particular library.  The library is a C++ library which imports glew.h and glx.h GLX redefines BOOL and that's not kosher since BOOL is a keyword for ObjC.

I had a fix the last time I went through this.  I #ifndef the header in the library to exclude GLEW and GLX and everything worked hunky-dory.

This time, however, I do the same thing, use the same #ifndef block but now it throws a bunch of errors.  I go back to the old project, and it works.  New project no-worky.

It seems like it does this every time, and my solution to it is new each time for some reason.  I know #defines and #includes are one of the trickiest areas of C++ (and cross-language with Objective-C), but I had this working and now it's not.

答:
A well adjusted person is one who makes the same mistake twice without getting nervous. - Alexander Hamilton

Seriously, though, if this has already happened a few times, that means that you will soon catch on. :)


问:
NoSQL and BIG DATA
I am doing an internship on Big Data technologies so I am new to this area. My question is about the use of NoSQL in the Big Data architecture. Do we need always to use a distributed storage (like HDFS in the case of Hadoop) then to put on top a NoSQL databases (like Hbase )?

I find it difficult to understand the typical BIG Data architecture specially for unstructured data .

If you can help me to see better I will be so thankful.

答: Using Distributed storage is helping to get the proper utilization of NoSQl technologies, if you need to utilize or take the full advantage of these technologies, with big data you must have to use distributed storage. </p>

Title: NoSQL and BIG DATA


问:
Would it make sense to use objects (instead of primitive types) for everything in C++?
During a recent project I've been working on, I've had to use a lot of functions that kind of look like this:

```<code>static bool getGPS(double plane_latitude, double plane_longitude, double plane_altitude,
                       double plane_roll, double plane_pitch, double plane_heading,
                       double gimbal_roll, double gimbal_pitch, double gimbal_yaw,
                       int target_x, int target_y, double zoom,
                       int image_width_pixels, int image_height_pixels,
                       double & Target_Latitude, double & Target_Longitude, double & Target_Height);
</code>```

So I want to refactor it to look something like this:

```<code>static GPSCoordinate getGPS(GPSCoordinate plane, Angle3D planeAngle, Angle3D gimbalAngle,
                            PixelCoordinate target, ZoomLevel zoom, PixelSize imageSize)
</code>```

This appears to me to be significantly more readable and safe than the first method.  But does it make sense to create PixelCoordinate and PixelSize classes? Or would I be better off just using std::pair<int,int> for each. And does it make sense to have a ZoomLevel class, or should I just use a double?

My intuition behind using classes for everything is based on these assumptions:

If there are classes for everything, it would be impossible to pass a ZoomLevel in where a Weight object was expected, so it would be more difficult to provide the wrong arguments to a function

Likewise, some illegal operations would cause compile errors, such as adding a GPSCoordinate to a ZoomLevel or another GPSCoordinate

Legal operations will be easy to represent and typesafe. i.e subtracting two GPSCoordinates would yield a GPSDisplacement

However, most C++ code I've seen uses a lot of primitive types, and I imagine there must be a good reason for that. Is it a good idea to use objects for anything, or does it have downsides that I am not aware of?

答:
Yes, definitely. Functions/methods that take too many arguments is a code smell, and indicates at least one of the following:

The function/method is doing too many things at once

The function/method requires access to that many things because it's asking, not telling or violating some OO design law

The arguments are actually closely related

If the last one is the case (and your example certainly suggests so), it's high time to do some of that fancy-pants "abstraction" that the cool kids were talking about oh, just some decades ago. In fact, I'd go further than your example and do something like:

```<code>static GPSCoordinate getGPS(Plane plane, Angle3D gimbalAngle, GPSView view)
</code>```

(I am not familiar with GPS so this is probably not a correct abstraction; for instance, I don't understand what zoom has to do with a function called getGPS.)

Please prefer classes like PixelCoordinate over std::pair<T, T>, even if the two have the same data. It adds semantic value, plus a bit of extra type safety (compiler will stop you from passing a ScreenCoordinate to a PixelCoordinate even though both are pairs.

Body:
Yes, definitely. Functions/methods that take too many arguments is a code smell, and indicates at least one of the following:

The function/method is doing too many things at once

The function/method requires access to that many things because it's asking, not telling or violating some OO design law

The arguments are actually closely related

If the last one is the case (and your example certainly suggests so), it's high time to do some of that fancy-pants "abstraction" that the cool kids were talking about oh, just some decades ago. In fact, I'd go further than your example and do something like:

static GPSCoordinate getGPS(Plane plane, Angle3D gimbalAngle, GPSView view)

(I am not familiar with GPS so this is probably not a correct abstraction; for instance, I don't understand what zoom has to do with a function called getGPS.)

Please prefer classes like PixelCoordinate over std::pair<T, T>, even if the two have the same data. It adds semantic value, plus a bit of extra type safety (compiler will stop you from passing a ScreenCoordinate to a PixelCoordinate even though both are pairs.


问:
Architecture change from using disk to RAM to read and write key/value pairs coming over a network
A WebApp writes a stream of data coming over a network to disk as key/value pair and then reads & send it over network again after few milliseconds in 99% of case. In 1% of cases write/read can be few hours to days apart (really don't know).

Latency is strict "no" in the app and we have to serve 100% of customers therefore I am planning to put data into RAM and later read and send it over network and only write to disk if the data is not read from RAM within a certain prefixed interval.

What could be possible solution to this problem?

P.S - Memcached looks like a good solution for using RAM instead of disk but Can memcached read/write of disk after time_to_live?

I also looking at Couchbase but I don't want to write to disk in all cases as 99% write/read happens in the matter of milliseconds.

Is it possible that after time_to_die Memcached could write the key/value to Couchbase instead of removing it from RAM and read it on demand?

[Edit 1]

After spending last few trying to explore various options. The following looks like a possible solution

Write the data stream simultaneously to the RAM (using Memcached) and disk using (GlusterFS).

In case the data is demanded by the application layer check it first in the RAM (Memcached) if it return the data ok, if it does not check the data on disk GlusterFS.

Remove data stream from RAM if data is demanded by application or when time_to_live is reached whichever is earlier.

Suggestion most welcome.

答:
To put the things simple. Use Redis and you will never speak of memcache again. Following are some plus points:

First of all in Redis you get the option to persist data in the disk.

Second, you have data structures like list, set etc. Also, supports atomic operations.


答:
Using dedicated types has the advantage that it's much harder to screw up the order of arguments. The first version of your example function, for example, begins with a chain of 9 doubles. When someone uses this function, it is very easy to screw up the order and pass the gimbal angles in place of the GPS coordinates and vice versa. This can lead to very strange and hard to trace bugs. When you pass only three arguments with different types instead, this error can be catched by the compiler.

I would in fact consider to go a step further and introduce types which are technically identical but have a different semantic meaning. For example by having a class PlaneAngle3d and a separate class GimbalAngle3d, even though both are a collection of three doubles. This would make it impossible to use one as the other, unless it's intentional.

I would recommend using typedefs which are just aliases for primitive types (typedef double ZoomLevel) not just for that reason, but also for another: It easily allows you to change the type later. When you get the idea one day that using float could be just as good as double but could be more memory- and CPU-efficient, you just have to change this in one place, and not in dozends.

Title: Would it make sense to use objects (instead of primitive types) for everything in C++?

Body:
During a recent project I've been working on, I've had to use a lot of functions that kind of look like this:

```<code>static bool getGPS(double plane_latitude, double plane_longitude, double plane_altitude,
                       double plane_roll, double plane_pitch, double plane_heading,
                       double gimbal_roll, double gimbal_pitch, double gimbal_yaw,
                       int target_x, int target_y, double zoom,
                       int image_width_pixels, int image_height_pixels,
                       double & Target_Latitude, double & Target_Longitude, double & Target_Height);
</code>```

So I want to refactor it to look something like this:

```<code>static GPSCoordinate getGPS(GPSCoordinate plane, Angle3D planeAngle, Angle3D gimbalAngle,
                            PixelCoordinate target, ZoomLevel zoom, PixelSize imageSize)
</code>```

This appears to me to be significantly more readable and safe than the first method.  But does it make sense to create PixelCoordinate and PixelSize classes? Or would I be better off just using std::pair<int,int> for each. And does it make sense to have a ZoomLevel class, or should I just use a double?

My intuition behind using classes for everything is based on these assumptions:

If there are classes for everything, it would be impossible to pass a ZoomLevel in where a Weight object was expected, so it would be more difficult to provide the wrong arguments to a function

Likewise, some illegal operations would cause compile errors, such as adding a GPSCoordinate to a ZoomLevel or another GPSCoordinate

Legal operations will be easy to represent and typesafe. i.e subtracting two GPSCoordinates would yield a GPSDisplacement

However, most C++ code I've seen uses a lot of primitive types, and I imagine there must be a good reason for that. Is it a good idea to use objects for anything, or does it have downsides that I am not aware of?


答:
Most big data technologies are distributed by design, because the idea of big data is that your database is too big and too frequented to be handled by one server alone.

But most distributed new database technologies (some of which might be called NoSQL) do not use a separate plattform like HDFS as distributed storage backend but come with their own. MongoDB, to name just one example, runs as different processes on multiple servers which communicate with each other to form clusters and shards.

Title: NoSQL and BIG DATA

Body:
I am doing an internship on Big Data technologies so I am new to this area. My question is about the use of NoSQL in the Big Data architecture. Do we need always to use a distributed storage (like HDFS in the case of Hadoop) then to put on top a NoSQL databases (like Hbase )?

I find it difficult to understand the typical BIG Data architecture specially for unstructured data .

If you can help me to see better I will be so thankful.


问:
Anonymous function performance - setTimeout
According to Gregory Baker & Erik Arvidsson (Google), creating a named function and then passing that to setTimeout is actually faster than creating an anonymous function (reference: Optimizing JavaScript code -> Avoiding pitfalls with closures):

Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

<snip>

```<code>    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }
</code>```

is slower than:

```<code>    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }
</code>```

In my testing, there does not appear to be any significant difference (jsPerf here), so why do they claim that creating a whole named function is faster than simply making an anonymous function?

EDIT: note that I am specifically referring to the last two examples, the first one has been removed for clarity.

答:
The theoretical difference comes from the fact the named function in your example is created at "compile" time.

But the real truth is that JavaScript engines are now very very good at creating and managing functions and scopes, which is arguably one of the most critical topic with today's coding style, so the overhead is generally totally insignificant.

In my opinion, this particular advice creates more harm (over optimized code) than good today. I see it as obsolete.


答:
Trust your instinct.

Some people get nervous in the face of a new assignment, large or small.  The answer that you found last time is still somewhere in your memory, regardless of your memory-recall works.

"Instinct" is often a proxy-word for the sub-conscious memory recall.  You might have an 'inclination,' 'an urge,' or similar.  Acting on those weak signals is more difficult in the presence of anxiety or other attention-consuming / attention-distracting factors.

Title: How do you keep from running into the same problems over and over?

Body:
I keep running into the same problems.  The problem is irrelevant, but the fact that I keep running into is completely frustrating.

The problem only happens once every, 3-6 months or so as I stub out a new iteration of the project.  I keep a journal every time, but I spend at least a day or two each iteration trying to get the issue resolved.

How do you guys keep from making the same mistakes over and over?

I've tried a journal but it apparently doesn't work for me.

[Edit]

A few more details about the issue:  Each time I make a new project to hold the files, I import a particular library.  The library is a C++ library which imports glew.h and glx.h GLX redefines BOOL and that's not kosher since BOOL is a keyword for ObjC.

I had a fix the last time I went through this.  I #ifndef the header in the library to exclude GLEW and GLX and everything worked hunky-dory.

This time, however, I do the same thing, use the same #ifndef block but now it throws a bunch of errors.  I go back to the old project, and it works.  New project no-worky.

It seems like it does this every time, and my solution to it is new each time for some reason.  I know #defines and #includes are one of the trickiest areas of C++ (and cross-language with Objective-C), but I had this working and now it's not.


问:
How to manage intermediate outputs efficiently?
I am implementing a C preprocessor in C...

I have the three functions:

trigraph replacing function

Line splicing function

comment removing function

However these functions work separately on files i.e.

First function will take a file and replace the trigraphs producing a temp-file1 as output

Second function will take temp-file1 as input and splice the lines and produce another temp-file2.

Third function will take temp-file2 as input and remove comment and produce yet another temp-file3.

And now the main preprocessing tasks will be performed on temp-file3 and a .i file will be produced as final output.

Now, I have 3 options :

Use temp files

use pipes

instead of intermediate temp-files or pipes use strings(i.e. whole temp-file1, 2 and 3 will be three big strings!!)

I have three doubts...

Option 1 seems less efficient than  option2

option 2 seems to be perfect but will I be limited by size of that unnamed pipe? (since I have single process i.e. function 1 2 & 3 will be called one after another) What if temp output size > pipe's total capacity?

option 3... Is it efficient, easy over previous two?

Please tell me, Which option should I choose?

答:
Option 1 is a way of allocating memory (in this case, from the page cache), with the following caveats:

if your temporary files aren't on the (a) temporary file system, your data will also be written pointlessly to disk

it's possible for other processes to read and maybe modify your temporary files

Option 2 won't work as stated: the pipe buffer will fill, and your write will block. Pipes are only safe if they're being read & written concurrently (whether by different processes, different threads, or suitably co-ordinated co-routines).

Option 3 is reasonable. Note that if your three functions can only shorten the file, you could simply re-write a single buffer in-place.


问:
Best way to lazy load blob from database in Java?
I have a database table that stores uploaded files (excel files) in a blob field. Each record contains the uploader, upload-time, the upload ID (primary key) and of-course, the blob itself.

At some point, I need to get that data from the database do something with it. Currently, I have a POJO which just mirrors the table structure and stores the file in a byte array, ie;

```<code>class Upload {
    private String ID;
    private ByteArray[] data;
    //Other fields and methods ommited for brevity
}
</code>```

As I am sure you will agree, this leaves the application open to memory issues if the file is particularly large. In reality, this file is unlikely to get so large as to cause a problem, but this definitely can't be considered a good design.

I have been trying to find what the best practices are for lazy-loading blob data but I am having trouble finding material that isn't about using particular application frameworks.

I am thinking I need to lose the 'data' field and just have a method, ie. getData(), that starts a new DB transaction to retrieve the blob returns an InputStream to it? See below for example, please let me know if there is a better way to do this..

```<code>public InputStream getData(){
    //Construct and execute SQL query.
    Blob blob = rs.getBlob(1);
    return blob.getBinaryStream();
}
</code>```

答:
the other thing you can do is caching the value after the first load so you don't need to keep going back to the data base

```<code>public InputStream getData(){
    if(data==null){
        //Construct and execute SQL query.
        Blob blob = rs.getBlob(1);
        data = blob.getBinaryStream();
    }
    return data;
}
</code>```

if you expect these blobs to be very large and want to be able to reclaim space while still keeping the record itself in memory you can use a WeakReference for the blob

```<code>private WeakReference<ByteArray[]> data;

public InputStream getData(){
    ByteArray[] local = data!=null?data.get():null;
    if(local==null){
        //Construct and execute SQL query.
        Blob blob = rs.getBlob(1);
        local = blob.getBinaryStream();
        data = new WeakReference<ByteArray[]>(local);
    }
    return local;
}
</code>```

Body:
the other thing you can do is caching the value after the first load so you don't need to keep going back to the data base

public InputStream getData(){
    if(data==null){
        //Construct and execute SQL query.
        Blob blob = rs.getBlob(1);
        data = blob.getBinaryStream();
    }
    return data;
}

if you expect these blobs to be very large and want to be able to reclaim space while still keeping the record itself in memory you can use a WeakReference for the blob

private WeakReference<ByteArray[]> data;

public InputStream getData(){
    ByteArray[] local = data!=null?data.get():null;
    if(local==null){
        //Construct and execute SQL query.
        Blob blob = rs.getBlob(1);
        local = blob.getBinaryStream();
        data = new WeakReference<ByteArray[]>(local);
    }
    return local;
}


答:
All three options have serious drawbacks.

As indicated by @Useless in his answer, temporary files have the drawback of doing needless disk access with the risk of external entities modifying the files.

Both option 2 and 3 limit the size of the files you can process. In option 2, this is limited by the internal buffer of the pipes and in option 3 it is limited by the amount of memory you have free.

I would advise to consider a fourth option:

You have listed for stages in the processing

trigraph processing

line splicing

comment removal

main preprocessing

Option 4 would be that each stage calls the function of the preceding stage to provide it with characters that have been processed up to that point.

So, the main preprocessing function requests characters from the comment removal function.

The comment removal function in turn requests characters from the line splicing function. If those characters indicate the start of a comment, more characters are requested until the entire comment has been seen. Those characters are discarded and a single space is returned to the caller. Characters outside comments are returned as-is.

The line splicing and trigraph processing functions work similarly, with the trigraph function being the only one that reads a file.

Title: How to manage intermediate outputs efficiently?

Body:
I am implementing a C preprocessor in C...

I have the three functions:

trigraph replacing function

Line splicing function

comment removing function

However these functions work separately on files i.e.

First function will take a file and replace the trigraphs producing a temp-file1 as output

Second function will take temp-file1 as input and splice the lines and produce another temp-file2.

Third function will take temp-file2 as input and remove comment and produce yet another temp-file3.

And now the main preprocessing tasks will be performed on temp-file3 and a .i file will be produced as final output.

Now, I have 3 options :

Use temp files

use pipes

instead of intermediate temp-files or pipes use strings(i.e. whole temp-file1, 2 and 3 will be three big strings!!)

I have three doubts...

Option 1 seems less efficient than  option2

option 2 seems to be perfect but will I be limited by size of that unnamed pipe? (since I have single process i.e. function 1 2 & 3 will be called one after another) What if temp output size > pipe's total capacity?

option 3... Is it efficient, easy over previous two?

Please tell me, Which option should I choose?


答:
option 4 is to refactor the functions so they can work on a stream and only process data as needed

in essence you call on function 3 if that needs more data it will call function 2 and if that needs more data it calls function 1 which reads directly from the input file; this will transform the preprocessor into a single pass instead of the 4-pass you have now

option 5 is concurrent processing, where you use a producer-consumer queue between the producing 1 and consuming 2 and a queue between the producing 2 and consuming 3, which produces for the main processing

option 5 will allow you to reuse more code as you can just replace all fwrites with pushes and all fread with polls (each blocking as the buffer fills up/gets empty) but you'll need to spawn a thread for each function


答:
So I want to refactor it to look something like this:

```<code>static GPSCoordinate getGPS(GPSCoordinate plane, Angle3D planeAngle, Angle3D gimbalAngle,
                        PixelCoordinate target, ZoomLevel zoom, PixelSize imageSize)
</code>```

This appears to me to be significantly more readable and safe than the first method.

It is [more readable]. It is also a good idea.

But does it make sense to create PixelCoordinate and PixelSize classes?

If they represent different concepts, it makes sense (that is, "yes.").

Or would I be better off just using std::pair for each.

You could start by doing typedef std::pair<int,int> PixelCoordinate, PixelSize;. This way, you cover the semantics (you're working with pixel coordinates and pixel sizes, not with std::pairs in your client code) and if you need to extend, you simply replace the typedef with a class and your client code should require minimal changes.

And does it make sense to have a ZoomLevel class, or should I just use a double?

You could typedef it as well, but I would use a double until I'd need functionality associated with it that doesn't exist for a double (for example, having a ZoomLevel::default value would require that you define a class, but until you have anything like that, keep it a double).

My intuition behind using classes for everything is based on these assumptions [omitted for brevity]

They are strong arguments (you should always strive to make your interfaces easy to use correctly and difficult to use incorrectly).

However, most C++ code I've seen uses a lot of primitive types, and I imagine there must be a good reason for that.

There are reasons; in lots of cases though, those reasons are not good. One valid reason to do this may be performance, but that means that you should see this kind of code as an exception, not as a rule.

Is it a good idea to use objects for anything, or does it have downsides that I am not aware of?

It is generally a good idea to make sure that if your values always appear together (and make no sense apart) you should group them together (for the same reasons you mentioned in your post).

That is, if you with coordinates that always have x, y, and z, then it's much better to have a coordinate class than transmit three parameters everywhere.

Body:
So I want to refactor it to look something like this:

static GPSCoordinate getGPS(GPSCoordinate plane, Angle3D planeAngle, Angle3D gimbalAngle,
                        PixelCoordinate target, ZoomLevel zoom, PixelSize imageSize)

This appears to me to be significantly more readable and safe than the first method.

It is [more readable]. It is also a good idea.

But does it make sense to create PixelCoordinate and PixelSize classes?

If they represent different concepts, it makes sense (that is, "yes.").

Or would I be better off just using std::pair for each.

You could start by doing typedef std::pair<int,int> PixelCoordinate, PixelSize;. This way, you cover the semantics (you're working with pixel coordinates and pixel sizes, not with std::pairs in your client code) and if you need to extend, you simply replace the typedef with a class and your client code should require minimal changes.

And does it make sense to have a ZoomLevel class, or should I just use a double?

You could typedef it as well, but I would use a double until I'd need functionality associated with it that doesn't exist for a double (for example, having a ZoomLevel::default value would require that you define a class, but until you have anything like that, keep it a double).

My intuition behind using classes for everything is based on these assumptions [omitted for brevity]

They are strong arguments (you should always strive to make your interfaces easy to use correctly and difficult to use incorrectly).

However, most C++ code I've seen uses a lot of primitive types, and I imagine there must be a good reason for that.

There are reasons; in lots of cases though, those reasons are not good. One valid reason to do this may be performance, but that means that you should see this kind of code as an exception, not as a rule.

Is it a good idea to use objects for anything, or does it have downsides that I am not aware of?

It is generally a good idea to make sure that if your values always appear together (and make no sense apart) you should group them together (for the same reasons you mentioned in your post).

That is, if you with coordinates that always have x, y, and z, then it's much better to have a coordinate class than transmit three parameters everywhere.


答:
I'd suggest determining what triggers the issue, and restructuring your development process to avoid that scenario. What 'restructuring' entails is highly dependent on the problem. It ranges from abstracting some behavior into a seperate class to changing the composition of your team.

A journal detailing the context of the incident and resolution approaches can certainly help you converge on the root cause and/or a general solution. Once you've determined that there are a few obvious options:

If the cause is avoidable: Try to avoid triggering the root cause next time.

If the solution proves to be simple: Implement the general solution whenever the problem occurs.

Restructure your development process so that it naturally avoids the issue.

The options available depend on the information about the issue you have, and the amount of control you have over the development process.


问:
Are there concrete reasons not to use libraries and code snippets heavily?
Overall I'm in programming for about 8 years now and it seems to me that I'm relying more and more on open source libraries and snippets (damn you GitHub!) to "get the job done". I know that in time I could write me own implementation but I like to focus on the overall design.

Is this normal (non corporate environment)? What could go wrong if my "programming" is nothing more than gluing different libraries together?

I know about "don't reinvent the wheel" but what happens when you don't invent a single wheel anymore?

答:
Does heavy library and code snippet usage make you a bad programmer?

If you use libraries and code snippets in appropriate places, then 'No', it does not mean you're a bad programmer. It means that you're a smart programmer who can apply the wisdom of others in appropriate places.

However...

It takes time to find libraries and code snippets, so if you can't write code on your own, and you need to spend hours to find libraries and code snippets to implement trivial tasks, then 'Yes', you are a bad programmer.


答:
Disclaimer: I prefer C to C++

Instead of classes, I would use structs. This point is pedantic at best, since structs and classes are nearly identical (see here for a simple chart, or this SO question), but I think there is merit in the differentiation.

C programmers are familiar with structs as blocks of data that have some greater meaning when grouped, whereas when I see a clasas, I assume there's some internal state and methods to manipulate that state. A GPS coordinate doesn't have state, just data.

From your question, it seems this is exactly what you're looking for, a general container, not a stateful structure. As the others have mentioned, I wouldn't bother putting Zoom into a class of its own; I personally hate classes built to hold a data type (my professors love creating Height and Id classes).

If there are classes for everything, it would be impossible to pass a ZoomLevel in where a Weight object was expected, so it would be more difficult to provide the wrong arguments to a function

I don't think this is a problem. If you reduce the number of parameters by grouping the obvious things like you've done, the headers should be enough to prevent those problems. If you're really worried, separate the primatives with a struct, which should give you compile errors for common mistakes. It's easy to swap two parameters next to each other, but harder if they're farther apart.

Likewise, some illegal operations would cause compile errors, such as adding a GPSCoordinate to a ZoomLevel or another GPSCoordinate

Good use of operator overloads.

Legal operations will be easy to represent and typesafe. i.e subtracting two GPSCoordinates would yield a GPSDisplacement

Also good use of operator overloads.

I think you're on the right track. Another thing to consider is how this fits into the rest of the program.


问:
Big project with many external libraries - source code organisation
I was wondering what is the best way to organize my source code. I was researching on SO and found https://stackoverflow.com/a/1398594/137261 but this source code layout is library specific and doesn't cover my situation.

My situation:

10 own modules (100k lines of code)

15 external libraries (e.g. boost, sqlite, zlib, etc.)

2 critical modules have to be available for selected developers only (maybe separate git repos ?)

project is multiplatform (Linux and Windows)

Git as version control system

cmake used to build project

Question:

does it make sense to incorporate all libraries into my project e.g. in _3rd_party_libs_ folder ?

how to handle lib include paths in my modules (environmental variable, relative paths, git submodules, etc. ) ?

should I always build external libs from source or just use their binaries ?

答:
does it make sense to incorporate all libraries into my project e.g. in _3rd_party_libs_ folder ?

Do whatever you want, but keep it consistent. I do note that you've listed examples such as boost/sqlite; these should be standard in your dev environments and not included in your project, unless you depend on say some funny version of boost.

how to handle lib include paths in my modules (environmental variable, relative paths, git submodules, etc. ) ?

This is what your build system - CMake - is for. Your source code just has #include <third_party_lib.h> without worrying about where they are located.

should I always build external libs from source or just used their binaries ?

Prefer binaries by default, unless you have a good reason to build from source every time.

OwnerDisplayName: tommyk


问:
Negative test cases confusion
In the Software testing book from Koirala, Sheihk, they say:

A positive test is when you put in a valid input and expect some
  action to be completed in accordance with the specification.

  A
  negative test is when you put in an invalid input and receive errors.

Part of my question:

Let's say there is a requirement: If the customer name=="James Bond", do something.

Is name<>"James Bond" negative or still positive test, verifying the requirement?

Or a login function:

Is correct login positive test case and incorrect negative?

Or Login failed is just confirmation of requirement that a password must be correct ->confirming invalid pass will not work.

For example, if the program is supposed to give an error when the person types in "101" on a field that should be between 1 and 100, then that is positive then if an error shows up. If, however, the application does not give an error when user types 101, then you have a negative test.

答:
Positive and negative is one nomenclature, true and false another. In general, you have to distinguish two things, which are both of a boolean nature:

Is the test itself written according to the requirements, or violating them? Let me refer to these as true and false from now on.

Is the test run successful or not? Let me refer to these as positive and negative from now on.

What your quote denotes as "positive" and "negative" are in fact only two of the possible four combinations. The quoted phrase "positive" means a true-positive result, i.e. valid input and a successful test result. Accordingly, "negative" means false-negative, i.e. invalid input and a failed test.

Result classifications

Here's a brief description for each of the four possible combinations and what is hidden behind them:

True-positive

The simplest case, in which your input is adhering to the specification and the result is as expected. Not much to say about these really.

True-negative

These are good, too. You have provided valid input, and the failing test tells you that there is something wrong in your product.

False-positive

These are monsters. They show up in your reports as green checkmarks, but really what the test is testing is not adhering to the specification.

False-negative

Again you are testing something which doesn't make sense, and you do it in a way that fails. The good point about these is that you at least become aware of the problem by a failing test.

Application to 101 Example

Let's apply this to your 101 example:

True tests

First, you write two test cases: Test #1 checks that for valid inputs, the user does not see an error message, whereas Test #2 checks that for input outside of the valid range an error is shown. Both tests adhere to the specification, hence, you can only end up with the true-cases below:

Test#1 True-positive: I enter 50 and no error shows up

Test#2 True-positive: I enter 101 and an error shows up

Test#1 True-negative: I enter 50, but an error shows up

Test#2 True-negative: I enter 101, but no error shows up

The negative cases both indicate that you have to fix your implementations.

False tests

Now consider two more tests: Test #3 checks that when you input a number between 1 and 100, an error message shows up. And Test #4 checks that no error message is shown when you enter 101. Both of these tests are not adhering to the specification! But you can still execute them, because they are just executable tests after all. Here are the possible cases:

Test #3 False-positive: I enter 50 and an error shows up

Test #4 False-positive: I enter 101 and no error shows up

Test #3 False-negative: I enter 50, but no error shows up

Test #4 False-negative: I enter 101, but an error shows up

As you can see, due to the nature of these tests you will never get a True-X result. The false-negative results are nicer, because they point you to the problem.

Impact on development

Our problem as developers is that we only get to see the result of test executions, for example in an IDE, as success or failure, which maps to the latter positive or negative. You do not get any indication of whether your test is true or false (because it is far from trivial to automatically determine that a test adheres to a specification).

True-negatives are relatively simple to fix: you just fix your code to do what the customer wants it to do.

False-negatives are more trouble: As it is really the test itself, which is at fault, you risk losing valuable time trying to turn a False-negative into a False-positive by "fixing" your product code.

False-positives are not a problem at the time they occur, but further down the road. Imagine that all your tests succeed, but several versions later that one tests suddenly fails. It has been working all the time, so you will assume that some recent code change broke it, but in fact, the test itself was already broken.

You might argue that the False-X variants of tests should not be created - and of course that's right. But they usually do not come into existence, because someone writes them, but rather, because someone wrote them long ago and now someone else has changed the requirements/specification. A simple example would be to change your example to allow 51-150 as valid input. A test that checks for an error for the input 200 remains a True-X test, but the test that tries to enter 101 and expects an error becomes a False-X. Gladly, it will fail.

More problematic is the test that enters 50 and expects no error. Due to the changed specification, 50 is no longer a valid input, but you will not find out that your application still accepts it as valid easily, because your test still says everything is alright. The specification change changed the test from a True-positive into a False-positive.

Lesson to be learned: when changing your specification make sure to update your tests as well.

References

The nomenclature of true/false-positive/negatives comes from statistics, especially, medical tests. They often have the problem, that tests are not as deterministic in their nature as it is the case for software, so they are also interested in sensitivity and specificity.

Another nomenclature (also in statistics) is to refer to the false-X cases as type I and type II errors.

Title: Negative test cases confusion


答:
From http://en.wikipedia.org/wiki/NoSQL

NoSQL database systems are often highly optimized for retrieval and appending operations and often offer little functionality beyond record storage (e.g. key–value stores). The reduced run-time flexibility compared to full SQL systems is compensated by marked gains in scalability and performance for certain data models.

In short, NoSQL database management systems are useful when working with a huge quantity of data when the data's nature does not require a relational model. The data can be structured, but NoSQL is used when what really matters is the ability to store and retrieve great quantities of data, not the relationships between the elements.

Do we need always to use a distibuted storage (like HDFS in the case of Hadoop) then to put on top a NoSQL databases (like Hbase )?

For large scale it is better to use distributed storage with NoSQL. But for small scale you can use ordinary storage system.

I find it difficult to understand the typical BIG Data architecture specially for unstructured data .

From http://en.wikipedia.org/wiki/Unstructured_data

Unstructured Data (or unstructured information) refers to information
  that either does not have a pre-defined data model and/or does not fit
  well into relational tables. Unstructured information is typically
  text-heavy, but may contain data such as dates, numbers, and facts as
  well. This results in irregularities and ambiguities that make it
  difficult to understand using traditional computer programs as
  compared to data stored in fielded form in databases or annotated
  (semantically tagged) in documents.

From http://en.wikipedia.org/wiki/Big_data

In information technology, big data is a collection of data sets so
  large and complex that it becomes difficult to process using on-hand
  database management tools or traditional data processing applications.

Big data usually includes data sets with sizes beyond the ability of
  commonly used software tools to capture, curate, manage, and process
  the data within a tolerable elapsed time. Big data sizes are a
  constantly moving target, as of 2012 ranging from a few dozen
  terabytes to many petabytes of data in a single data set. With this
  difficulty, new platforms of "big data" tools are being developed to
  handle various aspects of large quantities of data.

To understand BIG Data architecture specially for unstructured data, have a look how Giants work with Big Data.

For example, Google

http://architects.dzone.com/articles/big-data-beyond-mapreduce

http://www.techrepublic.com/blog/google-in-the-enterprise/googles-approach-to-big-data-is-bigquery/1660

For example, IBM

http://www-01.ibm.com/software/data/bigdata/enterprise.html

http://www.ibmbigdatahub.com/blog/saving-lives-1000-data-points-second

For example, Facebook

http://siliconangle.tv/video/how-facebook-uses-hadoop-overcome-big-data-challenges

Title: NoSQL and BIG DATA


答:
Fine answers here already, but there is one thing I would like to add:

Using PixelCoordinate and PixelSize class makes things very specific. A general Coordinate or Point2D class may probably better suit your needs. A Point2D should be a class implementing the most common point/vector operations. You could implement such a class even generically (Point2D<T> where T may be int or double or something else).

2D point/vector operations are so very common for lots of 2D geometry programming tasks that to my experience such a decision will increase highly the chance of reusing existing 2D operations. You will avoid the need for re-implementing them for each PixelCoordinate, GPSCoordinate, "Whatsover"-Coordinate class again and again.


问:
Is the "Gets or sets .." necessary in XML documentation of properties?
I am looking for a recommendation of a best practice for XML comments in C#. When you create a property, it seems like that the expected XML documentation has the following form:

```<code>/// <summary>
/// Gets or sets the ID the uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID {
    get;
    set;
}
</code>```

But since the signature of the property already tells you what operations are available to the external clients of the class (in this case it is both get and set) I feel like the comments are too chatty and that perhaps the following would be sufficient:

```<code>/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID {
    get;
    set;
}
</code>```

Microsoft uses the first form so it seems like it is an implied convention. But I think that the second one is better for the reasons I stated.

I understand that this quetion is an adept for being marked as not being constructive, but the amount of properties that one has to comment is huge and so I believe that this question has its right to be here.

I will appreciate any ideas or links to official recommended practices.

答:
I'd be happier with the more verbose version.

The other is like having a comment of "increment counter" after, well, incrementing a counter variable.

It is obvious there is a Get and Set. If you had a private setter, it'd be obvious as you would have the private keyword.

Comments should add value, not just be comment version of what the code actually is.


答:
The difference in Chrome, FF, IE10:

```<code>UserAgent           closure     nonclosure  static       # Tests
Chrome 25.0.1364    55,885,835  86,105,613  587,742,003  1
Firefox 19.0        31,856,561  67,442,015  863,300,987  1
IE 10.0             10,430,542  18,945,667  485,135,189  1
</code>```

In IE10 and Firefox, non-closure runs twice as fast and in Chrome almost twice as fast. Referencing a static function is an order of magnitude faster than either.

closure is defined as calling createClosure():

```<code>function createClosure() {
    var a = 'hi';
    return function() {
        alert(a);
    };
}
</code>```

nonclosure is defined as calling createNonClosure():

```<code>function createNonClosure() {
    return function() {
        alert('hi');
    };
}
</code>```

static is just referencing a static function, does not matter if it's named or not.

I am also pretty sure that closure gets slower when the environment being closed over gets bigger.

Here's the jsperf http://jsperf.com/closure-no-closure

Title: Anonymous function performance - setTimeout

Body:
According to Gregory Baker & Erik Arvidsson (Google), creating a named function and then passing that to setTimeout is actually faster than creating an anonymous function (reference: Optimizing JavaScript code -> Avoiding pitfalls with closures):

Creating a closure is significantly slower then creating an inner function without a closure, and much slower than reusing a static function. For example:

<snip>

```<code>    function alertMsg() {
      var msg = 'Message to alert';
      alert(msg);
    }
</code>```

is slower than:

```<code>    function setupAlertTimeout() {
      window.setTimeout(alertMsg, 100);
    }
</code>```

In my testing, there does not appear to be any significant difference (jsPerf here), so why do they claim that creating a whole named function is faster than simply making an anonymous function?

EDIT: note that I am specifically referring to the last two examples, the first one has been removed for clarity.

Body:
The difference in Chrome, FF, IE10:

UserAgent           closure     nonclosure  static       # Tests
Chrome 25.0.1364    55,885,835  86,105,613  587,742,003  1
Firefox 19.0        31,856,561  67,442,015  863,300,987  1
IE 10.0             10,430,542  18,945,667  485,135,189  1

In IE10 and Firefox, non-closure runs twice as fast and in Chrome almost twice as fast. Referencing a static function is an order of magnitude faster than either.

closure is defined as calling createClosure():

function createClosure() {
    var a = 'hi';
    return function() {
        alert(a);
    };
}

nonclosure is defined as calling createNonClosure():

function createNonClosure() {
    return function() {
        alert('hi');
    };
}

static is just referencing a static function, does not matter if it's named or not.

I am also pretty sure that closure gets slower when the environment being closed over gets bigger.

Here's the jsperf http://jsperf.com/closure-no-closure


答:
StyleCop uses the Gets or Sets ... notation which it enforces with rule SA1623.

The linked page lists another case you haven't listed:

```<code>/// <summary>
/// Gets a value indicating whether the item is enabled.
/// </summary>
public bool Enabled
{
    get { return this.enabled; }
}
</code>```

The other option you list would be.

```<code>/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID { get; set; }
</code>```

vs

```<code>/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID { get; }
</code>```

Which wouldn't provide information on the Intellisense hint that the property is read only, you could come up with a convention for this case too, but Gets ..., Gets or Sets... does the job nicely imo.

There are also other varients listed on the StyleCop rule which are clear by using the Gets or Sets... but might not be without.

Also when generating documentation from something like Doxygen or Sandcastle the full notation would document the API (for example) better.

Title: Is the "Gets or sets .." necessary in XML documentation of properties?

Body:
I am looking for a recommendation of a best practice for XML comments in C#. When you create a property, it seems like that the expected XML documentation has the following form:

```<code>/// <summary>
/// Gets or sets the ID the uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID {
    get;
    set;
}
</code>```

But since the signature of the property already tells you what operations are available to the external clients of the class (in this case it is both get and set) I feel like the comments are too chatty and that perhaps the following would be sufficient:

```<code>/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID {
    get;
    set;
}
</code>```

Microsoft uses the first form so it seems like it is an implied convention. But I think that the second one is better for the reasons I stated.

I understand that this quetion is an adept for being marked as not being constructive, but the amount of properties that one has to comment is huge and so I believe that this question has its right to be here.

I will appreciate any ideas or links to official recommended practices.

Body:
StyleCop uses the Gets or Sets ... notation which it enforces with rule SA1623.

The linked page lists another case you haven't listed:

/// <summary>
/// Gets a value indicating whether the item is enabled.
/// </summary>
public bool Enabled
{
    get { return this.enabled; }
}

The other option you list would be.

/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID { get; set; }

vs

/// <summary>
/// ID that uniquely identifies this <see cref="User" /> instance.
/// </summary>
public int ID { get; }

Which wouldn't provide information on the Intellisense hint that the property is read only, you could come up with a convention for this case too, but Gets ..., Gets or Sets... does the job nicely imo.

There are also other varients listed on the StyleCop rule which are clear by using the Gets or Sets... but might not be without.

Also when generating documentation from something like Doxygen or Sandcastle the full notation would document the API (for example) better.


答:
The only time I add information about the getting and setting of a property in the XML comments is when it doesn't behave as expected (straight public get and set).

If either are private or if they contain additional logic then I mention them, otherwise I just document the intent of the property.


答:
The signature may tell other pieces of code what operations are available; however, they are not clearly shown to the coder as he or she is working and XML documentation is meant for people to consume and not a compiler.

Take this class for example:

```<code>public class MyClass
{
    /// <summary>
    /// The first one
    /// </summary>
    public int GetOrSet { get; set; }

    /// <summary>
    /// The second one
    /// </summary>
    public int GetOnly { get; private set; }

    /// <summary>
    /// The last one
    /// </summary>
    public int SetOnly { set; private get; }
}
</code>```

When intellisense is pulled up to access one of these properties there is no indication which ones can be written to, read from, or both:

Likewise when viewing the documentation we also aren't quite sure:

As such we add the gets or sets, gets, or sets to make it easier on the programmer while writing the code. It certainly would not be write a large block of code that reads and processes some data only to find out that you cannot write that data back to the property as expected.

Body:
The signature may tell other pieces of code what operations are available; however, they are not clearly shown to the coder as he or she is working and XML documentation is meant for people to consume and not a compiler.

Take this class for example:

public class MyClass
{
    /// <summary>
    /// The first one
    /// </summary>
    public int GetOrSet { get; set; }

    /// <summary>
    /// The second one
    /// </summary>
    public int GetOnly { get; private set; }

    /// <summary>
    /// The last one
    /// </summary>
    public int SetOnly { set; private get; }
}

When intellisense is pulled up to access one of these properties there is no indication which ones can be written to, read from, or both:

Likewise when viewing the documentation we also aren't quite sure:

As such we add the gets or sets, gets, or sets to make it easier on the programmer while writing the code. It certainly would not be write a large block of code that reads and processes some data only to find out that you cannot write that data back to the property as expected.


问:
Architectural questions regarding, MV** frameworks, NoSQL data models, and gradual refactoring
I have a web app I would like to gradually refactor by adding structure to it.

I have narrowed down the options to Backbone (with some plugins), Ember.js and AngularJS

My goal is to refactor that app, which has the usual jQuery spaghetti and gradually add some structure to it.

Requirements

not a "all or nothing" framework, e.g. allow gradually moving code from "before" to "after" without rewriting the app from scratch (winner - Backbone?)

something that has  a future, people seem excited about and has a big company behind it (Angular takes this bullet)

Let me sometimes do things "my way" and not force a paradigm (Backbone a clear winner here)

Something that will really boost my productivity and remove the need for boilerplate code
(Angular + Ember)

Something that is good not just with the obvious things, but also the complex things, e.g. animation transitions, nested models, handling modal dialog views, drag and drop support, widget system etc

One option is to become an advanced developer in all 3 and then, the other is to ask people who did something similar

I know that with Backbone I can do everything I want, but I want to know if I'm not to "careful" and wonder if I'm not missing out by not taking the risk of using AngularJS / Ember.js

Questions

So my specific, answerable, constructive (as much as I could) questions are:

Is Angular / Ember able to support drag and drop without bending over backward?

Can either of these frameworks support animation transitions well?

Which of these 2 frameworks is easier to "add in" gradually and not to fully rewrite things "their way"

Which of these has better support for NoSQL /document based models as in MongoDB like documents (e.g. a JSON doc rather than a relational model)

Which of these has better built in support for complex models (similar to #4)

Both Ember Data, and Backbone-relational seem to come from a relational database paradigm, and I wonder if there is anything that can build a model from an arbitrary multilevel / nested tree like structure without having to define a NoSQL model in a relational like data structure (e.g. hasMany, belongsTo instead of just a JSON like document).

Also I don't want to stop using JqueryUI because it's not 100% done the "Ember way" or the "Angular way", is Backbone really my best option?
Are the nice bells and whistles that come with Angular / Ember are in a trade-off with flexibility?

Is it a good architectural choice to use either Angular or Ember when refactoring an existing jQuery callback pasta in a gradual, iterative approach?

答:
I think your question is missing a critical constraint, but you address it within the comments. Specifically, how much time do you have to invest in this refactor?

Time allotted is going to be the trump card requirement and renders your detailed questions a bit moot.

For this current refactoring window, you've been allocated one week. That's really not enough time to learn a brand new framework and complete meaningful refactoring for even a modest project. Adding in your outside time constraints, and you have perhaps 40 to 50 hours to apply.

That limited timeframe means you need to pick the framework you're most comfortable with now. Based upon your description and research, Backbone is the front runner for selection.

Yes, you may be "missing out" on some neat new feature of the other frameworks. Presuming that all three frameworks are "live" and still being developed, you're going to see that "lacking-feature" difference regardless of the framework you pick. The frameworks will keep moving forward even if you can't keep refactoring your project. Part of any design is to eliminate potential paths to follow so you can focus your top choice. An inherent part of that path elimination is that you will be missing out on feature XYZ that only the less attractive framework has. But that gets us back to time being your overriding constraint.

I would encourage laying out a prioritized list of areas that are going to be refactored. You need to include verification activities along with that refactoring, and I would encourage allowing for some schedule slack to handle the unexpected issues with conversion.


答:
Brownfield Application Development in .NET

shows developers how to approach legacy applications with the state-of-the-art concepts, patterns, and tools developers apply to new projects.


问:
Is using "out" or "ref" parameters in Java methods to return extra values bad?
I happened to create a mutable class like this:

```<code>class Mutable<T> {
    private T value;
    public Mutable() { this.value = null; }
    public Mutable(T value) { this.value = value; }
    T get() { return this.value; }
    void set(T value) { this.value = value; }
}
</code>```

And then it's often used in a method like this:

```<code>boolean operation(String input, Mutable<Set<String>> dataOut) throws ... {
    boolean result;
    try {
         String data = doSomething(input);
         result = validate(data);
         if (result && dataOut != null) {
             List<String> values = Arrays.asList(data.split(", "));
             Collections.sort(values);
             dataOut.set(new LinkedHashSet<String>(values));
         }
    } catch(SpecificIgnorableException ex) {
         result = false;
         logger.debug(ex);
    }
    return result;
}
</code>```

...which is just an example, could be any use case, where one would use ref or out parameters in C#, or non-const reference parameters in C++, or pointers to output parameters in C.

First, same could be done by using an array (with one element) instead of above custom type. Does it make sense to have this custom type which clearly states mutable, instead of using an implicitly mutable array?

Second, is this pattern bad and code smell in Java? Let's limit to cases where using out parameter would make sense in C#. Should every instance of this kind of Java code be replaced? With what?

答:
The real question is "are functions with side-effects bad?"

Providing a reference to an explicit mutable ("out") variable is no different than providing a Map that you modify, or referencing a global variable from within the function. In all three cases, the function is permitted to modify something in a way that is hard to reason about. Consider, for example, a function that modifies the "out" parameter, then throws.

The counter-argument is that this is no different from a method call that modifies an object's private state and then throws.

Personally, if I'm writing a method that is focused on a "result", I would prefer creating a new class to hold it; classes are cheap in Java. If I'm writing a method that modifies an object's internal state, I generally don't return anything from the method.


问:
Licensing: source code vs. production code in JavaScript
For commercial and licensing purposes, what is the correct wording for differentiating JavaScript source code (written by the programmer and including comments) from the minified version used in production?</p>

答:
I think you'll generally find it is called a debug build (example: KnockoutJS), or development build/version (example: BackboneJS), or "uncompressed build" (example: JQuery).

I think that all three variants are clear to anyone downloading them.


答:
First of all out and ref have nothing to do with each other.  An out parameter in C# is just the only way the language has of returning multiple values from a function, short of creating a new type to use as the return value.  Just because it's in the parameter list is only a syntax thing.  There's no equivalent in Java.

I think what you've got there is a code smell because it's not really idiomatic Java.  In your situation, I would just define a new class to use as a result value.

Title: Is using "out" or "ref" parameters in Java methods to return extra values bad?

Body:
I happened to create a mutable class like this:

```<code>class Mutable<T> {
    private T value;
    public Mutable() { this.value = null; }
    public Mutable(T value) { this.value = value; }
    T get() { return this.value; }
    void set(T value) { this.value = value; }
}
</code>```

And then it's often used in a method like this:

```<code>boolean operation(String input, Mutable<Set<String>> dataOut) throws ... {
    boolean result;
    try {
         String data = doSomething(input);
         result = validate(data);
         if (result && dataOut != null) {
             List<String> values = Arrays.asList(data.split(", "));
             Collections.sort(values);
             dataOut.set(new LinkedHashSet<String>(values));
         }
    } catch(SpecificIgnorableException ex) {
         result = false;
         logger.debug(ex);
    }
    return result;
}
</code>```

...which is just an example, could be any use case, where one would use ref or out parameters in C#, or non-const reference parameters in C++, or pointers to output parameters in C.

First, same could be done by using an array (with one element) instead of above custom type. Does it make sense to have this custom type which clearly states mutable, instead of using an implicitly mutable array?

Second, is this pattern bad and code smell in Java? Let's limit to cases where using out parameter would make sense in C#. Should every instance of this kind of Java code be replaced? With what?