答:
I have had sort a career path thats kind of the inverse of what you normally see. I started
as software support for scientifically challenging physics, then ended up working in the
intersection of architecture, programming, and algorithms for a computer company. After
that ran off I did performance optimization of a major engineering code for several years, but even that work ran out. Now, that I'm nearing retirement age I'm doing QA on the same code.
It is a combination of challenge, and drudgery. We have a really sharp new guy working 100% on bug fixes, and I spend a lot of working with him. It is a challenging position, and you can learn a lot doing it. At this point my main interest in profesional development is for my twin boys, who are comp sci college freshman. So I have new interest in learning (or relearning) stuff that will be relevant to their careers, especially applied math. I have a different perspective of things now that I am concerned with QA/validation, wheras for the previous quarter century it was speed,speed,speed at any cost.</p>

Title: Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?

Body:
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?


问:
How to handle divide by zero in a language that doesn't support exceptions?
I'm in the middle of developing a new programming language to solve some business requirements, and this language is targeted at novice users. So there is no support for exception handling in the language, and I wouldn't expect them to use it even if I added it.

I've reached the point where I have to implement the divide operator, and I'm wondering how to best handle a divide by zero error?

I seem to have only three possible ways to handle this case.

Ignore the error and produce 0 as the result. Logging a warning if possible.

Add NaN as a possible value for numbers, but that raises questions about how to handle NaN values in other areas of the language.

Terminate the execution of the program and report to the user a severe error occurred.

Option #1 seems the only reasonable solution. Option #3 is not practical as this language will be used to run logic as a nightly cron.

What are my alternatives to handling a divide by zero error, and what are the risks with going with option #1.

答:
Disallow it in the language. That is to say, disallow dividing by a number until it's provably not zero, usually by testing it first. Ie.</p>

```<code>int div = random(0,100);
int b = 10000 / div; // Error E0000: div might be zero
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Disallow it in the language. That is to say, disallow dividing by a number until it's provably not zero, usually by testing it first. Ie.

int div = random(0,100);
int b = 10000 / div; // Error E0000: div might be zero


问:
Why does the modifier access for the properties need to be public with Unity?
Why does the modifier access for the properties need to be public with Unity?

I'm very interested in a detailed explanation for my question. I read about tips to do it in other ways, but not a detailed explanation about why this can't be declared explicitly in my code.

答:
Why would you need to inject private properties?  That's not what DI is for.  Injecting private properties would violate encapsulation.

One of the constructor overloads on your class should specify everything the class needs to instantiate.  If the class can't specify what it needs in it's public API, then it doesn't need it.

From http://natpryce.com/articles/000783.html (emphasis mine):

There are two aspects to Dependency Injection. Firstly, an object's
  interface should define the services that the object requires as well
  as those it provides. Secondly, the code that satisfies the
  requirements of an object by giving it a reference to the services of
  is collaborators is external to both the object and its collaborators.
  For this reason, the pattern also used to be called "third-party
  binding" or "third-party connect": some third party is responsible for
  connecting and satisfying the service requirements of a component (the
  party of the first part) with those provided by another component (the
  party of the second part).

The name "Dependency Injection" only relates to the second aspect. And
  worse, makes it sound like dependencies are "injected" through the
  object's encapsulation boundary rather than explicitly defined as part
  of the object's API. And so we get "dependency injection" APIs, like
  that in JavaEE 5, which use reflection to poke dependencies into an
  object's private fields, bypassing the constructor, adding a great
  deal of complexity to client & test code while not providing the
  benefits that the Dependency Injection pattern should deliver.


问:
Why would someone use @Native annotations?
link : http://download.java.net/jdk8/docs/api/java/lang/annotation/Native.html

In Java 8, there will be @Native annotations.

Indicates that a field defining a constant value may be referenced from native code. The annotation may be used as a hint by tools that generate native header files to determine whether a header file is required, and if so, what declarations it should contain.

Problem is: What for?
Do you have any idea on which problematics would be efficiently solved by this feature?

答: Imagine a header which defines constants to be used in messaging. One party of the conversation might be developed in C++, and they'd like to #include a header. Now maintaining two similar but separate files is a risk; deriving the C++ header from @Native constants is safer.


问:
Arrays vs Objects in view template
I am wondering, in view templates, what would contribute to me choosing between using arrays or objects for getting things printed out in arrays

{{$user->zip_code}} vs {{$user['zip_code']}}

I'm working in blade templates in Laravel/PHP fwiw.

My feeling is that it makes sense to use objects: we can use methods if we need to to display/format data, it looks a lot cleaner in the views, and bc of how PHP works fails gracefully if the item isn't set (an unset array value will puke, so you either need to make sure all possible properties are present but false, or do a {{(isset($user['zip_code'])) ? $user['zip_code'] : ''}} for everything you use in a view.

However, I have encountered some contrasting opinions like:
the less the view knows about the layers below it, the better. As such, "flat" values (arrays) are better to use in the view.
We should not trust the view not to explode if a value is not set, that should be handled in the controller.

Because our object properties are not encoded in the models in this system, we can't rely on each object always having the same info in a model level.

Wondering if there are other factors at play here. Orr.. Does it not matter

答:
It's a developer perception. The OOP design concept was introduced in PHP with introduction to version 5 and has been a successful one.
At the initial level the use of array seems to be much easier than the use of Objects due to the use of pointer notation instead of dot notation as in other OOP based languages.
But as you move ahead on the platform OBJECTS will be more preferred way of handling data. It makes the code much better to be maintained in the larger complex system and easier for the other developers from PHP background to understand.</p>

Title: Arrays vs Objects in view template


问:
What's up with the Class::get(id) idiom in PHP
I am a new PHP developer (coming from .NET). The experienced php dev that I work with said that calling a static get method on a PHP class with an ID as a parameter is common in PHP.

Is there a name for this idiom? Is there a reason why developers do this? Can someone point to a link to an example class?

I would like to understand more of what he is saying. He is talking about code like this I think, to pull car #1 from the database:

```<code>$car = Car::get(1)
</code>```

答:
This is the facade pattern and the purpose is to provide easy access to common or otherwise complicated tasks. Generally it just provides syntatic sugar. To compare it to the C# world think of it like extension methods:

Example of calculating the total transaction amount for a user traditionally:

```<code>var total = 0f;
foreach(var transaction in User.transactions) {
    total += transaction.Amount;
}
</code>```

Using an extension method:

```<code>// Extension Method
public static float AccountBalance(this User user) {
    var total = 0f;
    foreach(var transaction in User.transactions) {
        total += transaction.Amount;
    }
    return total;
}

// Using the extension method
user.AccountBalance();
</code>```

Likewise the same sort of thing happens using the facade pattern in PHP:

```<code>$total = 0;
foreach($user->trasnactions as $transaction) {
    $total += $transaction->amount;
}
</code>```

With a facade

```<code><?php
class User {
    public static function TotalTransactionSum($userid) {
        $user = $userRepository->getById($userid);
        $total = 0;
        foreach($user->transaction as $transaction) {
            $total += $transaction->amount;
        }
        return $total;
    }
}

// Using the facade later
$total = User::TotalTransactionSum(1);
</code>```

Body:
This is the facade pattern and the purpose is to provide easy access to common or otherwise complicated tasks. Generally it just provides syntatic sugar. To compare it to the C# world think of it like extension methods:

Example of calculating the total transaction amount for a user traditionally:

var total = 0f;
foreach(var transaction in User.transactions) {
    total += transaction.Amount;
}

Using an extension method:

// Extension Method
public static float AccountBalance(this User user) {
    var total = 0f;
    foreach(var transaction in User.transactions) {
        total += transaction.Amount;
    }
    return total;
}

// Using the extension method
user.AccountBalance();

Likewise the same sort of thing happens using the facade pattern in PHP:

$total = 0;
foreach($user->trasnactions as $transaction) {
    $total += $transaction->amount;
}

With a facade

<?php
class User {
    public static function TotalTransactionSum($userid) {
        $user = $userRepository->getById($userid);
        $total = 0;
        foreach($user->transaction as $transaction) {
            $total += $transaction->amount;
        }
        return $total;
    }
}

// Using the facade later
$total = User::TotalTransactionSum(1);


答:
Object or array is of little consequence here really, they are just there to provide the view with a data store that it can access. What is important is that you are providing the view with data designed for the view and not simply reusing other objects because it feels like they fit. A User is different to your authentication service than it is to your view.

It may seem convenient to simply pass the same User object that is used in authentication to the view and display the username on the page; however, when you want to be able to also display a nickname later on you'll then be introducing a nickname property into your authentication service. Likewise when you go to test your view you would then have to mock the User object that including information for authentication when really you just wanted to display the anme.

A better method would be to create a ViewModel class (or array) and add the user's information to this. Pass this object to your view. Now if you want to add a nickname you do not need to alter anything with the authentication service, you simply need to pull the nickname from the appropriate data store into your view model and continue on. Likewise now that the view is using its own model you can provide sensible defaults to display in the event that there's an error (for example the user can't be found in the database).

Title: Arrays vs Objects in view template

Body:
I am wondering, in view templates, what would contribute to me choosing between using arrays or objects for getting things printed out in arrays

{{$user->zip_code}} vs {{$user['zip_code']}}

I'm working in blade templates in Laravel/PHP fwiw.

My feeling is that it makes sense to use objects: we can use methods if we need to to display/format data, it looks a lot cleaner in the views, and bc of how PHP works fails gracefully if the item isn't set (an unset array value will puke, so you either need to make sure all possible properties are present but false, or do a {{(isset($user['zip_code'])) ? $user['zip_code'] : ''}} for everything you use in a view.

However, I have encountered some contrasting opinions like:
the less the view knows about the layers below it, the better. As such, "flat" values (arrays) are better to use in the view.
We should not trust the view not to explode if a value is not set, that should be handled in the controller.

Because our object properties are not encoded in the models in this system, we can't rely on each object always having the same info in a model level.

Wondering if there are other factors at play here. Orr.. Does it not matter


问:
Better OOP in Javascript - multiple methods or methods with options?
Let's say I have an object like this:

```<code>function Foo() {
  this.parser = new DataParser();
};
</code>```

Within Foo I have a method that does something like this:

```<code>Foo.prototype.getResponse = function(message, callback) {
  var payload = {data: message, type: 'normal'};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

Now, let's say that somewhere else I need to call foo.getResponse(). Most of the time I want it to run just like this, but on occasion I need the format of the payload to be slightly different - let's say I need to specify a different type.

Would it be better to make a different method for this slightly different kind of request, like so...

```<code>Foo.prototype.getSimilarResponse = function(message, callback) {
  var payload = {data: message, type: 'other'};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

... or to take an option on getReponse, like so...

```<code>Foo.prototype.getSimilarResponse = function(message, type, callback) {
  var payload = {data: message, type: type};
  var response = this.parser.parse(payload, function(data){
    callback(data);
  });
}
</code>```

... or to do something else entirely?

Using a type option in the example above is a lot more DRY, but I don't like the way it requires the caller to know about payload type, which is really the concern of Foo and doesn't need to be exposed anywhere else.

How would you recommend approaching a situation like the above?

答:
See also:

The Options Argument

This is very popular in the jQuery community. It's handy when you have a lot of potential for variation that might result in a ton of args which happens all the time in UI functionality.

I'm also fond of it for regular higher-level app architecture constructors. The ease of mashing objects like these together is one of the reasons inheritance is much less exclusively relied on in JS.

One of the nicer side-effects is the self-documenting factor of having an easy-to-read list of things spelling out what all the variable options are and it's really easy to add new ones without having to make changes anywhere but the function/constructor.

```<code>function Carousel(optionsIn){
    var options = {
        loopsItems:true, //first item follows last if true, or you're just stopped if false
        itemsPerScroll:'visible', //or a set number
        horizontal:true, //false is vertical
        contentInjection:false //static HTML if false, or a URL, or array of HTML
    };

    optionsIn = optionsIn || {};

    for(var x in optionsIn){
        options[x] = optionsIn[x];
    }
    //or $.extend(options, optionsIn) in jQuery land
    //behavior defined/switched on options here...

}
</code>```

The Arguments Keyword

Lots of cool uses, especially for variable numbers of arguments.

```<code>function addThingsToSomeArray(){ //first arg is array, followed by any number of things
    var
        thingsLen = arguments.length-1,
        someArray = arguments[0]
    ;
    while(i--){
        someArray.unshift(arguments[i+1]);
    }
}

var someArray = [];
addThingsToSomeArray(someArray, function yay(){alert('yay');}, 'Bob', new Date(), Infinity);
</code>```

Look on and become green with envy, ye of strictly-typed languages that protect you from learning a lesson once the hard way occasionally in favor of helping you to do it wrong successfully over and over again.

Body:
See also:

The Options Argument

This is very popular in the jQuery community. It's handy when you have a lot of potential for variation that might result in a ton of args which happens all the time in UI functionality.

I'm also fond of it for regular higher-level app architecture constructors. The ease of mashing objects like these together is one of the reasons inheritance is much less exclusively relied on in JS.

One of the nicer side-effects is the self-documenting factor of having an easy-to-read list of things spelling out what all the variable options are and it's really easy to add new ones without having to make changes anywhere but the function/constructor.

function Carousel(optionsIn){
    var options = {
        loopsItems:true, //first item follows last if true, or you're just stopped if false
        itemsPerScroll:'visible', //or a set number
        horizontal:true, //false is vertical
        contentInjection:false //static HTML if false, or a URL, or array of HTML
    };

    optionsIn = optionsIn || {};

    for(var x in optionsIn){
        options[x] = optionsIn[x];
    }
    //or $.extend(options, optionsIn) in jQuery land
    //behavior defined/switched on options here...

}

The Arguments Keyword

Lots of cool uses, especially for variable numbers of arguments.

function addThingsToSomeArray(){ //first arg is array, followed by any number of things
    var
        thingsLen = arguments.length-1,
        someArray = arguments[0]
    ;
    while(i--){
        someArray.unshift(arguments[i+1]);
    }
}

var someArray = [];
addThingsToSomeArray(someArray, function yay(){alert('yay');}, 'Bob', new Date(), Infinity);

Look on and become green with envy, ye of strictly-typed languages that protect you from learning a lesson once the hard way occasionally in favor of helping you to do it wrong successfully over and over again.


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

Earlier this evening I gave an answer to a question on StackOverflow.

The question:

Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. I want to change his debt. Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ?

My answer:

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object.

Example situation:

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}
```

<p><em>A comment I received:</em></p>

<blockquote>
  <p>Business logic should really be in a service. Not in a model.</p>
</blockquote>

<p><strong>What does the internet say?</strong></p>

<p>So, this got me searching since I've never really (consciously) used a service layer.
I started reading up on the Service Layer pattern and the Unit Of Work pattern but so far I can't say I'm convinced a service layer has to be used.</p>

<p>Take for example this article by Martin Fowler on the anti-pattern of an Anemic Domain Model:</p>

<blockquote>
  <p>There are objects, many named after the nouns in the domain space, and these objects are connected with the rich relationships and structure that true domain models have. The catch comes when you look at the behavior, and you realize that there is hardly any behavior on these objects, making them little more than bags of getters and setters. Indeed often these models come with design rules that say that you are not to put any domain logic in the the domain objects. Instead there are a set of service objects which capture all the domain logic. These services live on top of the domain model and use the domain model for data.</p>

  <p>(...)  The logic that should be in a domain object is domain logic - validations, calculations, business rules - whatever you like to call it.</p>
</blockquote>

<p>To me, this seemed exactly what the situation was about: I advocated the manipulation of an object's data by introducing methods inside that class that do just that. However I realize that this should be a given either way, and it probably has more to do with how these methods are invoked (using a repository).</p>

<p>I also had the feeling that in that article (see below), a Service Layer is more considered as a façade that delegates work to the underlying model, than an actual work-intensive layer.</p>

<blockquote>
  <p>Application Layer [his name for Service Layer]: Defines the jobs the software is supposed to do and directs the expressive domain objects to work out problems. The tasks this layer is responsible for are meaningful to the business or necessary for interaction with the application layers of other systems. This layer is kept thin. It does not contain business rules or knowledge, but only coordinates tasks and delegates work to collaborations of domain objects in the next layer down. It does not have state reflecting the business situation, but it can have state that reflects the progress of a task for the user or the program.</p>
</blockquote>

<p>Which is reinforced here:</p>

<blockquote>
  <p>Service interfaces. Services expose a service interface to which all inbound messages are sent. You can think of a service interface as a façade that exposes the business logic implemented in the application (typically, logic in the business layer) to potential consumers.</p>
</blockquote>

<p>And here:</p>

<blockquote>
  <p>The service layer should be devoid of any application or business logic and should focus primarily on a few concerns. It should wrap Business Layer calls, translate your Domain in a common language that your clients can understand, and handle the communication medium between server and requesting client.</p>
</blockquote>

<p>This is a serious contrast to other resources that talk about the Service Layer:</p>

<blockquote>
  <p>The service layer should consist of classes with methods that are units of work with actions that belong in the same transaction.</p>
</blockquote>

<p>Or the second answer to a question I've already linked:</p>

<blockquote>
  <p>At some point, your application will want some business logic. Also, you might want to validate the input to make sure that there isn't something evil or nonperforming being requested. This logic belongs in your service layer.</p>
</blockquote>

<p><strong>"Solution"?</strong></p>

<p>Following the guidelines in this answer, I came up with the following approach that uses a Service Layer:</p>

<pre class="lang-cs prettyprint-override"><code>class UserController : Controller {
    private UserService _userService;

    public UserController(UserService userService){
        _userService = userService;
    }

    public ActionResult MakeHimPay(string username, int amount) {
        _userService.MakeHimPay(username, amount);
        return RedirectToAction("ShowUserOverview");
    }

    public ActionResult ShowUserOverview() {
        return View();
    }
}

class UserService {
    private IUserRepository _userRepository;

    public UserService(IUserRepository userRepository) {
        _userRepository = userRepository;
    }

    public void MakeHimPay(username, amount) {
        _userRepository.GetUserByName(username).makePayment(amount);
    }
}

class UserRepository {
    public User GetUserByName(string name){
        // Get appropriate user from database
    }
}

class User {
    private int debt; // debt in cents
    private string name;

    // getters

    public void makePayment(int cents){
        debt -= cents;
    }
}
</code>```

Conclusion

All together not much has changed here: code from the controller has moved to the service layer (which is a good thing, so there is an upside to this approach). However this doesn't look like it had anything to do with my original answer.

I realize design patterns are guidelines, not rules set in stone to be implemented whenever possible. Yet I have not found a definitive explanation of the service layer and how it should be regarded.

Is it a means to simply extract logic from the controller and put it inside a service instead?

Is it supposed to form a contract between the controller and the domain?

Should there be a layer between the domain and the service layer?

And, last but not least: following the original comment

Business logic should really be in a service. Not in a model.

Is this correct?

How would I introduce my business logic in a service instead of the model?

答:
The tl;dr version:

My experiences and opinions say that any objects which have business logic should be part of the domain model. The data model should likely not have any logic whatsoever. Services should likely tie the two together, and deal with cross-cutting concerns (databases, logging, etc.). However, the accepted answer is the most practical one.

The longer version, which has kind of been alluded to by others, is that there is an equivocation on the word "model". The post switches between data model and domain model as if they're the same, which is a very common mistake. There may also be a slight equivocation on the word "service".

In practical terms, you should not have a service which makes changes to any domain objects; the reason for this is that your service will likely have some method for every property on your object in order to change the value of that property. This is a problem because then, if you have an interface for your object (or even if not), the service is no longer following the Open-Closed Principle; instead, whenever you add more data to your model (regardless of domain vs data), you end up having to add more functions to your service. There are certain ways around it, but this is the most common reason I've seen "enterprise" applications fail, especially when those organizations think that "enterprise" means "have an interface for every object in the system". Can you imagine adding new methods to an interface, then to two or three different implementations (the in-app one, the mock implementation, and debug one, the in-memory one?), just for a single property on your model? Sounds like a terrible idea to me.

There's a longer problem here that I won't go into, but the gist is this: Hardcore object-oriented programming says that no one outside of the relevant object should be able to change the value of a property within the object, nor even "see" the value of the property within the object. This can be alleviated by making the data read-only. You can still run into issues like when a lot of people make use of the data even as read-only and you have to change the type of that data. It's possible that all the consumers will have to change to accommodate that. This is why, when you make APIs to be consumed by anyone and everyone, you're advised not to have public or even protected properties/data; it's the very reason OOP was invented, ultimately.

I think the majority of the answers here, aside from the one marked accepted, are all clouding the issue. The one marked accepted is good, but I still felt the need to reply and agree that bullet 4 is the way to go, in general.

In DDD, services are meant specifically for the situation when you have an operation that doesn't properly belong to any aggregate root. You have to be careful here, because often the need for a service can imply that you didn't use the correct roots. But assuming you did, a service is used to coordinate operations across multiple roots, or sometimes to handle concerns that don't involve the domain model at all...

ContentLicense: CC BY-SA 4.0


问:
When are Getters and Setters Justified?
Getters and setters are often criticized as being not proper OO. On the other hand, most OO code I've seen has extensive getters and setters.

When are getters and setters justified? Do you try to avoid using them? Are they overused in general?

If your favorite language has properties (mine does) then such things are also considered getters and setters for this question. They are the same thing from an OO methodology perspective. They just have nicer syntax.

Sources for Getter/Setter Criticism (some taken from comments to give them better visibility):

http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html

http://typicalprogrammer.com/?p=23

http://c2.com/cgi/wiki?AccessorsAreEvil

http://www.darronschall.com/weblog/2005/03/no-brain-getter-and-setters.cfm

http://www.adam-bien.com/roller/abien/entry/encapsulation_violation_with_getters_and

http://www.yegor256.com/2014/09/16/getters-and-setters-are-evil.html

To state the criticism simply: Getters and Setters allow you to manipulate the internal state of objects from outside of the object. This violates encapsulation. Only the object itself should care about its internal state.

And an example

Procedural version of code:

```<code>struct Fridge
{
    int cheese;
}

void go_shopping(Fridge fridge)
{
     fridge.cheese += 5;
}
</code>```

Mutator version of code:

```<code>class Fridge
{
     int cheese;

     void set_cheese(int _cheese) { cheese = _cheese; }
     int get_cheese() { return cheese; }
 }

void go_shopping(Fridge fridge)
{
     fridge.set_cheese(fridge.get_cheese() + 5);
}
</code>```

The getters and setters made the code much more complicated without affording proper encapsulation. Because the internal state is accessible to other objects we don't gain a whole lot by adding these getters and setters.

The question has been previously discussed on Stack Overflow:

https://stackoverflow.com/questions/565095/java-are-getters-and-setters-evil

https://stackoverflow.com/questions/996179

答:
If getters and setters violate encapsulation and true OO, then I'm seriously in trouble.

I always felt an object represents whatever best comes to mind that you need it to do.

I have just finished writing a program that generates Mazes in Java, and I have class that represents "Maze Squares". I have data in this class that represents coordinates, walls and booleans etc.

I have to have some way to change/manipulate/access this data! What do I do without getters and setters? Java doesn't use properties and setting all my data that is local to this class to public is DEFINITELY a violation of encapsulation and OO.

Title: When are Getters and Setters Justified?


问:
How does rapid prototyping fit into an agile methodology?
I work for a large company, which dictates the use of agile processes. For example, for our projects, we use cloud-based services that are specifically targeted at managing agile development.

The specific engineering group I work for has not traditionally developed software (instead we help drive projects from a much more birds-eye point of view), but that is changing. We have a wide range of upcoming/planned software projects that are mostly data-centric - e.g., we will be doing data monitoring, collection, aggregation, and some reporting. Other tasks involve automation with specialized hardware and various types of client/server (multitiered) architectures. I am to assist in the process of hiring several people, and formulating many of our plans in moving forward.

My question is whether or not doing rapid prototyping (throwaway code) fits into an agile philosophy. For example, I love Python and its wide range of packages. I see the possibility of implementing many of our ideas very quickly with a Python based workflow. However, I think that there will be a lot of perceptions that Python is not "enterprise-quality", and much of this work would need to be rewritten in Java or maybe C++.

However, creating the Python prototypes would give us a lot of bang for our buck in enabling us to quickly deliver real results.

Have you been able to incorporate rapid prototyping - hopefully in Python - into a solid agile workflow in an enterprise environment?

答:
Isn't rapid prototyping (i.e. iterative and incremental development) sort of the whole point of Agile?

It sounds like you're having issues with "perception is reality" at your organization.  You might want to remind everyone that Agile doesn't mean "throw out all plans," any more than Test-Driven Development means "throw out all architecture."

And Python is not (if it ever was) a toy language.  NASA and its contractors use Python, and if it's good enough for them, it's good enough for me.


问:
How to explain to my manager the importance of separation of concerns?
I'm an extremely novice web programmer working at a 2 person shop building websites, and we're in the process of writing a simple website template system in PHP from scratch. My manager is entirely self taught. He has been insisting that we put our HTML directly quoted in variables, mixing our back end code with the front end stuff.

```<code>$foo = "<html>
        <body>
            <div class=\"bar\">" . $bar . "</div>
        </body>
        </html>";

echo $foo;
</code>```

He claims that it is easier to work with this way. I insisted that we should at least use PHP tags in our HTML, rather than the HTML in the PHP.

```<code><html>
<body>
    <div class="bar"><?php echo $bar; ?></div>
</body>
</html>
</code>```

I feel like this is a real pain in the ass to read and it just looks like a mess. I think it would be a lot easier to separate the logic from the presentation, but he is certain that his way is best. How can I explain the importance of this so that he will understand? I can't put it into words, exactly.

EDIT: Think you guys could leave a comment when you're down voting me? I have no idea how to fix my question if you just down vote it and leave without suggesting improvements.

答:
Reasons:

The designer and PHP programmer can't work on their respective concerns at the same time. That means high potential for scenarios where one person will have to wait for the other to be done or if you're actually using version control run into a merge conflict all of which needlessly take time, which costs $$$s

It limits options for a white-labeling approach where you have similar front ends being served by mostly the same back-end. That may unexpectedly reduce the value of the app to a given customer who decides to split their brand leading to a decision to not use you again which costs you $$$s

Similarly you may find your markup is almost perfect for another project requiring only new CSS and some minor tweaks and find replaces but bad-news-bears, it's hoplessly spliced and intertwined with your server-side code rather than only at spots where the server actually adds conent so you won't have that option costing you more time which as we know turns into $$$s

It flies in the face of almost universal convention, meaning even if you're sure you're right and everybody else is wrong, they're still going to think your firm is inept when they're devs or future devs see that code which costs you $$$s

It does look terrible. On the client-side where you can have several languages and lord knows how many silly things from templating and down-compiling/help-you-not-suck-at-css dependencies, we keep 'em separated for legibility/sanity. Stop by the JavaScript chat room on SE and ask folks there how many have ADD. We freaking all do. Keep it clean so our heads don't explode. Otherwise it would take us longer to remember what the crap 3-5 languages we were trying to process simultaneously and understand what we're looking at which means it takes us longer which costs you $$$s

You're not alone among UI devs. Very few of us would consider that no biggie. I get pissed when opening and closing tags aren't found in the same damn template. Harder to attract and keep enthusiastic talent when you decide your way is better than widely acknowledged convention which yes, does indeed cost more $$$s

Note the pattern. Relate the stuff you care about to how it results in costs. He likely won't give a damn if he's resisted as much accidental knowledge of best practices as he has in the process of learning how to build a website with PHP, but it's usually the best/only way if there is one.


问:
How to properly deprecate methods in Java?
Today I lost a method that I was using since my co-worker redefined it to take its superclass instead. So after synchronizing with the repository I had trouble. Would it had been better in this case to use some annotation like @Deprecated instead of removing the method so that I would get an error message telling my that the method was deprecated? Can a version control system or an IDE work around situations like this by deprecating methods instead of deleting them?

答: For Java, I'm not sure the specifics of deprecation beyond the @Deprecated annotation. To answer your question, I am not aware of Git at least being able to adequately and clearly deprecate methods themselves (I may have not come into contact with them). In my experience, wholesale removing methods may be a bad idea, as you yourself were used to using them; annotating a class as @Deprecated may help in the transition period to the new build so all team members can clearly see where that method has gone and why. Commenting the annotation as to when, why and how the method has been deprecated may be a good idea too.


问:
Term to describe keyword followed by statement block
Is there a general term to describe a keyword followed by a statement block?  E.G.

```<code>if() {statement block}
while() {statement block}
try{statement block}
finally{statement block}
</code>```

Or even something made up:  controlScope{statement block}

答: I'd call them "Block Identifiers". In languages that support it, they are typically lexical closures which makes them more or less equivalent to functions. Thus they are "named functions" rather than anonymous functions which would be something like "BlockVariable = {block}".</p>


答:
@Deprecated annotation is the correct thing to do.  Removing code creates breaking changes in the API that is being used - this can be bad.

The thing is that often people ignore the 'bad' thing and still use deprecated methods because it doesn't fail the build.  Thus, the next correct thing to do is to make using deprecated methods fail the build.

It is possible to make the build scripts often used by Java developers to fail the build on compiler warnings (not only errors).  There are various approaches to doing this depending on the build system being used (gradle, maven, ant, ...).

At the point that you now fail the build when (unconsciously) using the deprecated method (you upgraded the library, something is now deprecated, the build fails - this is a good thing).

At that point, you can specifically disable deprecated warning for that method call with @SuppressWarnings( "deprecation" ) and then it will build again.  But now you know that you need to fix that code, because your build failed and that alerted you to the changing API.

Title: How to properly deprecate methods in Java?

Body: Today I lost a method that I was using since my co-worker redefined it to take its superclass instead. So after synchronizing with the repository I had trouble. Would it had been better in this case to use some annotation like @Deprecated instead of removing the method so that I would get an error message telling my that the method was deprecated? Can a version control system or an IDE work around situations like this by deprecating methods instead of deleting them?


答:
Deprecation is not designed for within a single project in a team environment; it's designed for published APIs. Within a single project, it's can be useful as shown in Mothermole1's answer to indicate that there is a better way of using that API now. This question has some suggestions on how to properly document why the method/class was deprecated and what should be used as an alternative.

I'd be interested to learn some more about the circumstances under which the offending method was removed. In my mind the length of time that code has been around and how core it is to the app determines how much ceremony should be attached to its removal. If it's used in one other place and is fairly new, I wouldn't expect any process for its removal. However, if it's been around for years and is part of a core class that is used throughout the app, I would expect some discussion as to how to best handle the transition.

There are a couple ways to do that. If the method in question is part of a public API that is exported outside the app, the best way is usually to deprecate the method in one release and then remove it in the next. Often for backwards compatibility you might never remove the method; you would just make it clear that it isn't supported anymore. In an internal API, depending on how pervasive the use is and how complex it is to change I'd just remove it and fix all the callers. In cases where the call is used in many places and is difficult to change deprecation is probably a safer bet - just be sure to recognize the technical debt you may be adding to the project since you'll now have two different ways of doing things. You may want to consider a migration strategy in which you would transition the code over a longer period of time.


问:
Would it be a good idea to work on letting people add arrays of numbers in javascript?
I am a very mathematically oriented programmer, and I happen to be doing a lot of java script these days.  I am really disappointed in the math aspects of javascript:

the Math object is almost a joke because it has so few methods

you can't use ^ for exponentiation

the + operator is very limited, you cant add array's of numbers or do scalar multiplication on arrays

Now I have written some pretty basic extensions to the Math object and have considered writing a library of advanced Math features, amazingly there doesn't seem to be any sort of standard library already out even for calculus, although there is one for vectors and matricies I was able find.

The notation for working with vectors and matricies is really bad when you can't use the + operator on arrays, and you cant do scalar multiplication.  For example, here is a hideous expression for subtracting two vectors, A - B:

```<code>Math.vectorAddition(A,Math.scalarMultiplication(-1,B));
</code>```

I have been looking for some kind of open-source project to contribute to for awhile, and even though my C++ is a bit rusty I would very much like to get into the code for V8 engine and extend the + operator to work on arrays, to get scalar multiplication to work, and possibly to get the ^ operator to work for exponentiation.  These things would greatly enhance the utility of any mathematical javascript framework.

I really don't know how to get involved in something like the V8 engine other than download the code and start working on it.  Of course I'm afraid that since V8 is chrome specific, that without browser cross-compatibility a fundamental change of this type is likely to be rejected for V8.  I was hoping someone could either tell me why this is a bad idea, or else give me some pointers about how to proceed at this point to get some kind of approval to add these features.

Thanks!

答:
You've hit on the two things that actually bum me out about JS sometimes. Wimpy numbers and no operator overloading. One of JS's strengths however is ease of creating a less tedious interface than the perhaps more verbose/self-documenting interfaces from core functionality (or any icky interface you don't want to deal with for that matter). Here's a  simple chaining addition interface I whipped up. I think I'd rather just add a subtract method and chain as necessary but when it sees a '-' it will subtract the next vector arg and its args are also overloaded to handle dropping an interface vector object directly in so stuff like this should work:

```<code>var vec1 = $v([1,2,3]);

vec1.val();//[1,2,3];
vec1.add([1,1,1],[1,1,1]).val();// [3,4,5]
vec1.add('-',[2,2,2]).val();// [1,2,3]

var vec2 = $([3,2,1]).add(vec1,[1,1,1],'-',[2,2,2]).val(); // [5,5,5]
</code>```

And the func:

```<code>function $v(vector){ //produce basic chaining add/subtract wrapper

    return new VectorInterface(vector);

    function VectorInterface(vectorVal){

        if(!validateVector(vectorVal)){
            vectorVal = [0,0,0]; //no idea if you would want this as a default
        }
        //vectorVal is persistent

        //I use function hoisting to keep interface declaration clean
        this.val = val;
        this.add = add;
        //this.subtract = subtract; //so we can subtract without cheesy '-' args later

        //public methods

        function val(){
            return vectorVal;
        }

        function add(){
            var
                argLen = arguments.length,
                mod = 1
            ;

            for(var i=0; i < argLen; i++){

                var thisArg = arguments[i];

                if(thisArg.constructor.name === VectorInterface){
                    thisArg = thisArg.val();
                }

                if(validateVector(thisArg)){
                    vectorVal[0]+= mod * thisArg[0];
                    vectorVal[1]+= mod * thisArg[1];
                    vectorVal[2]+= mod * thisArg[2];
                    mod = 1;
                }
                else if(thisArg='-'){
                    mod=-1;
                }
            }
            return this; //make it chainable for addition of other methods
        }

        //internal
        function validateVector(vec){
            if((vec !== undefined) && (vec.length !== undefined) && ( vec.length === 3 )){
                return true;
            }
            else { return false; }
        }
    };

}
</code>```

It wouldn't be that hard to add other operator methods or further overload the args to identify arrays of array vectors and chew through them as appropriate when added to the args.

Body:
You've hit on the two things that actually bum me out about JS sometimes. Wimpy numbers and no operator overloading. One of JS's strengths however is ease of creating a less tedious interface than the perhaps more verbose/self-documenting interfaces from core functionality (or any icky interface you don't want to deal with for that matter). Here's a  simple chaining addition interface I whipped up. I think I'd rather just add a subtract method and chain as necessary but when it sees a '-' it will subtract the next vector arg and its args are also overloaded to handle dropping an interface vector object directly in so stuff like this should work:

var vec1 = $v([1,2,3]);

vec1.val();//[1,2,3];
vec1.add([1,1,1],[1,1,1]).val();// [3,4,5]
vec1.add('-',[2,2,2]).val();// [1,2,3]

var vec2 = $([3,2,1]).add(vec1,[1,1,1],'-',[2,2,2]).val(); // [5,5,5]

And the func:

function $v(vector){ //produce basic chaining add/subtract wrapper

    return new VectorInterface(vector);

    function VectorInterface(vectorVal){

        if(!validateVector(vectorVal)){
            vectorVal = [0,0,0]; //no idea if you would want this as a default
        }
        //vectorVal is persistent

        //I use function hoisting to keep interface declaration clean
        this.val = val;
        this.add = add;
        //this.subtract = subtract; //so we can subtract without cheesy '-' args later

        //public methods

        function val(){
            return vectorVal;
        }

        function add(){
            var
                argLen = arguments.length,
                mod = 1
            ;

            for(var i=0; i < argLen; i++){

                var thisArg = arguments[i];

                if(thisArg.constructor.name === VectorInterface){
                    thisArg = thisArg.val();
                }

                if(validateVector(thisArg)){
                    vectorVal[0]+= mod * thisArg[0];
                    vectorVal[1]+= mod * thisArg[1];
                    vectorVal[2]+= mod * thisArg[2];
                    mod = 1;
                }
                else if(thisArg='-'){
                    mod=-1;
                }
            }
            return this; //make it chainable for addition of other methods
        }

        //internal
        function validateVector(vec){
            if((vec !== undefined) && (vec.length !== undefined) && ( vec.length === 3 )){
                return true;
            }
            else { return false; }
        }
    };

}

It wouldn't be that hard to add other operator methods or further overload the args to identify arrays of array vectors and chew through them as appropriate when added to the args.


答:
You're going to throw the code away and not put it into production (make that perfectly clear to EVERYONE), so being agile or not doesn't really matter. Any agile practices are purely optional for prototypes: sprints, burn-downs, testing, pair-programming or whatever else you plan on using.

If you're mainly going to be building functional models in Python to help product owners and other decision makers to conceptualize the project, you don't need to be enterprise ready.  However, if you're creating proof of concept or trying to see if you can handle certain performance levels, you should probably stick to the production language. That doesn't mean you can't try it in Python.

Regardless, you're going to throw the code away, but have the knowledge of being able to make this work along with a better sense of what the owners want. Now you can use any methodolgy you want.

Title: How does rapid prototyping fit into an agile methodology?

Body:
I work for a large company, which dictates the use of agile processes. For example, for our projects, we use cloud-based services that are specifically targeted at managing agile development.

The specific engineering group I work for has not traditionally developed software (instead we help drive projects from a much more birds-eye point of view), but that is changing. We have a wide range of upcoming/planned software projects that are mostly data-centric - e.g., we will be doing data monitoring, collection, aggregation, and some reporting. Other tasks involve automation with specialized hardware and various types of client/server (multitiered) architectures. I am to assist in the process of hiring several people, and formulating many of our plans in moving forward.

My question is whether or not doing rapid prototyping (throwaway code) fits into an agile philosophy. For example, I love Python and its wide range of packages. I see the possibility of implementing many of our ideas very quickly with a Python based workflow. However, I think that there will be a lot of perceptions that Python is not "enterprise-quality", and much of this work would need to be rewritten in Java or maybe C++.

However, creating the Python prototypes would give us a lot of bang for our buck in enabling us to quickly deliver real results.

Have you been able to incorporate rapid prototyping - hopefully in Python - into a solid agile workflow in an enterprise environment?


问:
Do support sites like Stack Overflow upset the paid-support open source model?
In order to stay relevant in the marketplace, I'm researching new business models for my software company.  The open source model with paid support seems like a good fit for our product, but I have concerns about whether or not a paid support model is viable in an era where top-notch help is readily available for free on sites like those in the Stack Exchange network.

Case in point -- I moved my employees to Ubuntu last year because I didn't want to pay for Win 7 licenses and new hardware (plus, the mono platform was highly attractive).  My staff had no Linux experience, but were able to achieve relative competency in about 120 days with the help of AskUbuntu, Stack Overflow, and a few "For Dummies" books.  We did employ an Ubuntu consultant for 7 days to provide training and support, but beyond that spent $0.00 on any kind of paid expertise.

In regards to my due diligence, I ran a 3 month beta of the freemium-paid-support model with one of our smaller customers, and achieved mediocre results.  I'd like to think its because our software is so stable and easy to use that the customer didn't need much paid support, but I suspect that they circumvented the terms of our SLA in the same manner that we did with the move to Ubuntu.

Does anyone out there has any thoughts, advice, or experience relevant to the move I'm considering?  What worked, what didn't, etc?

答:
There is no "paid-support open source model".  At least, there isn't much of a one.  A very small number of individual people have been able to make the model work, and an even smaller number of companies.  It works when the software has high value or risk profiles compared to the purchase price of its competitors.  It also works when the company involved presses hard to get commercial users to pay up (e.g., MySQL and Red Hat Enterprise Linux).

As you yourself demonstrated, most users of open source software won't spend money on it.


问:
Use the filesystem or some noSql database for shared memory between processes?
I'm implementing a system that's basically a pipeline of XML documents: XML documents are retrieved over the Internet, validated, further processed etc. until they are ingested in a relational (non-XML) database. After the ingestion in the database they can be discarded.

Since the various components of the pipeline are somewhat independent from each other I want to use a number of separate applications, each performing a "step" in the pipeline. What should be the reasoning behind choosing the file-system for data sharing between the above applications versus some noSQL database?

The data to be shared is mostly XML files and total volume of data that goes through the pipeline maybe 10 gigabytes per day.

答:
I'd recommend some kind of message queue system. Each XML document enters the queue and is processed asynchronously by a consumer. The consumer can then save the data into the database or publish the document to the next consumer's queue, depending on what rules you have set up in your system.

Consumers may work on a single document at a time or you might even have multiple consumers processing documents in parallel at each step.

There are a number of Java libraries for implementing message queues:

Open MQ

RabbitMQ

OpenJMS


答:
What if 20% of users were willing to pay for the support before StackOverflow, but only 10% after StackOverflow, but due to free support on StackOverflow 5 times as many people are using the given system then would otherwise be the case?

As there is no cost for users that don’t pay for the support, a "paid-support open source model" tends to make more money, the more users there are.

Another way to think of it is, a group of programmers creates a toolkit, they could be charging out support at $300 a day and have to employ lots of support people, or they could do a lot less days of support at $2000 a day and have more fun while StackOverflow picks up the basic support.

Take home profit and enjoyment for the founders of a company does not always scale with the turnover of the company – so having somewhere else to point low value customers can be of benefit to everyone.

Title: Do support sites like Stack Overflow upset the paid-support open source model?

Body:
In order to stay relevant in the marketplace, I'm researching new business models for my software company.  The open source model with paid support seems like a good fit for our product, but I have concerns about whether or not a paid support model is viable in an era where top-notch help is readily available for free on sites like those in the Stack Exchange network.

Case in point -- I moved my employees to Ubuntu last year because I didn't want to pay for Win 7 licenses and new hardware (plus, the mono platform was highly attractive).  My staff had no Linux experience, but were able to achieve relative competency in about 120 days with the help of AskUbuntu, Stack Overflow, and a few "For Dummies" books.  We did employ an Ubuntu consultant for 7 days to provide training and support, but beyond that spent $0.00 on any kind of paid expertise.

In regards to my due diligence, I ran a 3 month beta of the freemium-paid-support model with one of our smaller customers, and achieved mediocre results.  I'd like to think its because our software is so stable and easy to use that the customer didn't need much paid support, but I suspect that they circumvented the terms of our SLA in the same manner that we did with the move to Ubuntu.

Does anyone out there has any thoughts, advice, or experience relevant to the move I'm considering?  What worked, what didn't, etc?


问:
What's the most absurd myth about programming issues?
To put it another way... What is the most commonly held and frustrating misunderstanding about programming, you have encountered?

Which widespread and longstanding myths/misconceptions do you find hard for programmers to dispel/correct.

Please, explain why this is a myth.

答: Manufacturing lessons can be applied to the software development process.</p>

ContentLicense: CC BY-SA 2.5


问:
Do you believe it's a good idea for Software Engineers to have to work as Quality Assurance Engineers for some period of time?
I believe it is.  Why?

I've encountered many Software Engineers who believe they are somehow superior to QA engineers.  I think it may help quench this belief if they do the job of a QA engineer for some time, and realize that it is a unique and valuable skill-set of its own.

The better a Software Engineer is at testing their own programs, the less cost in time their code incurs when making its way through the rest of the software development life-cycle.

The more time a Software Engineer spends thinking about how a program can break, the more often they are to consider these cases as they are developing them, thus reducing bugs in the end product.

A Software Engineer's definition of "complete" is always interesting...if they have spent time as a QA engineer maybe this definition will more closely match the designer of the software's.

Note I make above suggestion with a small time-frame in mind as I am aware having someone work in a position that is not the position they are hired for is definitely a recipe for losing that developer.

What do you all think?

答:
Not necessarily - both programmers and testers are required to have different skills. Just because you are a good programmer does not mean you can be a good tester (many people dont understand that, but being a programmer does not automatically qualify you to be a tester).

A great tester needs to have really devilish skills, be able to do things that the software was not designed to do, but can expect the user to do in the real world. That takes skill, patience, ability to see what can go wrong where, an understanding of the user's mentality and so many other factors.

Note that I use the words programmer and tester - but if you are a software engineer and not yet decided whether you want to be a programmer or a tester, then it encompasses both these things and hence yes, you should have experience in both at least in the first few years of your life before taking the decision.

That does not mean that you take an experienced programmer and make him test for a while just to make him understand how hard the QA engineers work.


问:
Understanding abstraction
I am trying to understand object oriented code better and I decided to start at abstraction. If I am not incorrect, abstraction means that you hide information that isn't relevant to what task you want to perform, i.e. If I turn on the TV I would not need to know the internal that is going on.

Or If I have a class that handles Orders, and I would like to get the Total cost of a couple of Products, a getTotal() method would be the only thing that the User needs to know about to get the total sum of the products, and not how it's actually calculated.

So per se, by using a class I am abstracting data?

答:
Hiding data is more Encapsulation, really.  Abstraction is about hiding implementation details.

For example, let's say we want to add two numbers together.  Unless you've done a fair bit of studying of electronic engineering,  you probably have no idea just how complex such a simple problem is.

First, the compiler turns your instruction x = y + z into machine code that loads two values into two registers in the CPU, then executes an ADD instruction, retrieves the result from the register, and stores it back into memory.  And that ADD instruction requires some complicated logic gates to function properly, and those logic gates are built out of transistors and semiconductors, which have to be engineered to very exacting specifications based on the laws of quantum mechanics...

...but you don't really care about any of that.  All you care about is being able to write the code and get the right answer.  The programming language is an abstraction that covers up the details of how the machine code really works, and the machine code is an abstraction that covers up the details of how the underlying electronics work, and so on.  As long as it works, you don't really need to worry about how, and that makes your job as a programmer a lot simpler!

On a somewhat higher level, let's say you want a way to save data to a file, and load it from a file.  Well, there are filesystem APIs in your OS for that.  But what if you also want your program to be able to download a file from the Internet and process it?  You could always download it and save it to a file, and then use your code to load it from a file, but that's kind of wasteful and overly complicated, especially if the user doesn't actually need your program to leave that file on their hard drive.

So instead, you can use an abstraction: a stream.  The idea of a stream is "I have this sequence of data that can be read or written to in order."  Note how it doesn't say anything about the underlying representation of the data.  So if you rework your code to deal with streams instead of files, it suddenly becomes much more versatile.  Now you can read from a file by giving the code a FileStream object, or work with a download by giving the exact same code a HTTPStream object, or even work with data held entirely in local memory with a MemoryStream object.  The code that's processing the stream doesn't need to know anything about files anymore; it just needs to know about the data that the stream contains.  By abstracting away the details ("the data is saved to a file") your job as a programmer becomes easier, and your code becomes more flexible.

Title: Understanding abstraction


问:
Ordering if conditions for efficiency and clean code
This is purely a design question and the example is simple to illustrate what I am asking and there are too many permutations of more complex code to provide examples that would cover the topic. I am not referring specifically to this example, just using the example to illustrate what I am referring to.

In an if statement, is there a preferred way to order conditions, in terms of coding convention and, more importantly, efficiency?

For such a simple example, efficiency will not be an issue, but I am not asking for a code review per se, but an understanding of the concept.

Two alternatives:

1.

```<code>public double myStuff(int i)
{
    // check for an invalid number of tourists
    if (i > 0)
    {
        // do something here

        return doubleSomething;
    } else
    {
        return Double.NaN;
    }
}
</code>```

2.

```<code>public double myStuff(int i)
{

    if (i <= 0)
    {
        return Double.NaN;

    } else
    {

        {
            // do something here

            return doubleSomething;
        }
</code>```

If the if statement was to become more complex, and possibly nested, in what order should conditions be addressed?

答:
When it comes to large if blocks, optimization isn't really an issue. The compiler will generate pretty much the same result no matter how you organize them, assuming that the conditions are equally easy to calculate.

One technique I like to use is to use "guard statements" to check for invalid input right away, at the top of the method body. This way, the rest of the method can be formatted with the assumption that the arguments are already valid.

```<code>public double myStuff(int i, SomeOtherArgument widget) {
    // Perform any simple checks for invalid data right away and
    // fail fast if something smells bad.
    if (i <= 0)
        return Double.NaN;
    if (widget == null)
        throw new IllegalArgumentException();

    // If the stuff you've done above this line is trivial, there's no reason
    // to wrap the rest of the method body in a big else block. It's just noise.

    return doABunchOfWork();
}
</code>```

Body:
When it comes to large if blocks, optimization isn't really an issue. The compiler will generate pretty much the same result no matter how you organize them, assuming that the conditions are equally easy to calculate.

One technique I like to use is to use "guard statements" to check for invalid input right away, at the top of the method body. This way, the rest of the method can be formatted with the assumption that the arguments are already valid.

public double myStuff(int i, SomeOtherArgument widget) {
    // Perform any simple checks for invalid data right away and
    // fail fast if something smells bad.
    if (i <= 0)
        return Double.NaN;
    if (widget == null)
        throw new IllegalArgumentException();

    // If the stuff you've done above this line is trivial, there's no reason
    // to wrap the rest of the method body in a big else block. It's just noise.

    return doABunchOfWork();
}


问:
Why doesn't Python allow multi-line lambdas?
Can someone explain the concrete reasons why BDFL choose to make Python lambdas single line?

This is good:

```<code>lambda x: x**x
</code>```

This results in an error:

```<code>lambda x:
    x**x
</code>```

I understand that making lambda multi-line would somehow "disturb" the normal indentation rules and would require adding more exceptions, but isn't that worth the benefits?

Look at JavaScript, for example. How can one live without those anonymous functions? They're indispensable. Don't Pythonistas want to get rid of having to name every multi-line function just to pass it as an argument?

答:
I know this is super old, but putting here as a reference.

An alternative to using lambda could be to use a def in a non-conventional way.  The goal is to pass a def to a function, which can be done in only one circumstance -- a decorator.  Notice that with this implementation def result does not create a function, it creates the result of reduce(), which ends up being a dict.

Shameless plug: I do a lot of this here.

>>> xs = [('a', 1), ('b', 2), ('a', 3), ('b', 4)]
>>> foldl = lambda xs, initial: lambda f: reduce(f, xs, initial)
>>> @foldl(xs, {})
... def result(acc, (k, v)):
...     acc.setdefault(k, 0)
...     acc[k] += v
...     return acc
...
>>> result
{'a': 4, 'b': 6}
```

<p>Note that multi-statement lambdas <em>can</em> be done, but only with really, really ugly code.  However, what is interesting is how scoping works with this implementation (note the multiple usage of the <code>name</code> variable and the shadowing of the <code>message</code> variable.</p>

<pre class="lang-py prettyprint-override"><code>>>> from __future__ import print_function
>>> bind = lambda x, f=(lambda x: x): f(x)
>>> main = lambda: bind(
...     print('Enter your name.'), lambda _: bind(
...     raw_input('> '), lambda name: bind(
...     'Hello {}!'.format(name), lambda message: bind(
...     print(message), lambda _: bind(
...     'Bye {}!'.format(name), lambda message: bind(
...     print(message)
... ))))))
>>> main()
</code>```

Enter your name.
> foo
Hello foo!
Bye foo!
```

Body:
I know this is super old, but putting here as a reference.

An alternative to using lambda could be to use a def in a non-conventional way.  The goal is to pass a def to a function, which can be done in only one circumstance -- a decorator.  Notice that with this implementation def result does not create a function, it creates the result of reduce(), which ends up being a dict.

Shameless plug: I do a lot of this here.

>>> xs = [('a', 1), ('b', 2), ('a', 3), ('b', 4)]
>>> foldl = lambda xs, initial: lambda f: reduce(f, xs, initial)
>>> @foldl(xs, {})
... def result(acc, (k, v)):
...     acc.setdefault(k, 0)
...     acc[k] += v
...     return acc
...
>>> result
{'a': 4, 'b': 6}

Note that multi-statement lambdas can be done, but only with really, really ugly code.  However, what is interesting is how scoping works with this implementation (note the multiple usage of the name variable and the shadowing of the message variable.

>>> from __future__ import print_function
>>> bind = lambda x, f=(lambda x: x): f(x)
>>> main = lambda: bind(
...     print('Enter your name.'), lambda _: bind(
...     raw_input('> '), lambda name: bind(
...     'Hello {}!'.format(name), lambda message: bind(
...     print(message), lambda _: bind(
...     'Bye {}!'.format(name), lambda message: bind(
...     print(message)
... ))))))
>>> main()

Enter your name.
> foo
Hello foo!
Bye foo!


问:
Is there any "real" reason multiple inheritance is hated?
I've always liked the idea of having multiple inheritance supported in a language.  Most often though it's intentionally forgone, and the supposed "replacement" is interfaces.  Interfaces simply do not cover all the same ground multiple inheritance does, and this restriction can occasionally lead to more boilerplate code.

The only basic reason I have ever heard for this is the diamond problem with base classes.  I just can't accept that.  To me, it comes off an awful lot like, "Well, it's possible to screw it up, so it's automatically a bad idea."  You can screw up anything in a programming language though, and I mean anything.  I just cannot take this seriously, at least not without a more thorough explanation.

Just being aware of this problem is 90% of the battle.  Furthermore I think I heard something years ago about a general-purpose work-around involving an "envelope" algorithm or something like that (does this ring a bell, anyone?).

Concerning the diamond problem, the only potentially genuine problem I can think of is if you're trying to use a third-party library and can't see that two seemingly unrelated classes in that library have a common base class, but in addition to documentation, a simple language feature could, let's say, require that you specifically declare your intent to create a diamond before it'll actually compile one for you.  With such a feature, any creation of a diamond is either intentional, reckless, or because one is unaware of this pitfall.

So that all being said...Is there any real reason most people hate multiple inheritance, or is it all just a bunch of hysteria that causes more harm than good?  Is there something that I am not seeing here?  Thank you.

Example

Car extends WheeledVehicle, KIASpectra extends Car and Electronic, KIASpectra contains Radio.  Why doesn't KIASpectra contain Electronic?

Because it is an Electronic.  Inheritance vs. composition should always be an is-a relationship vs. a has-a relationship.

Because it is an Electronic.  There are wires, circuit boards, switches, etc. all up and down that thing.

Because it is an Electronic.  If your battery goes dead in the winter, you're in just as much trouble as if all your wheels suddenly went missing.

Why not use interfaces?  Take #3, for instance.  I don't want to write this over and over again, and I really don't want to create some bizarre proxy helper class to do this either:

private void runOrDont()
{
    if (this.battery)
    {
        if (this.battery.working && this.switchedOn)
        {
            this.run();
            return;
        }
    }
    this.dontRun();
}
```

(We're not getting into whether that implementation is good or bad.)  You can imagine how there may be several of these functions associated with Electronic that are not related to anything in WheeledVehicle, and vice-versa.

I wasn't sure whether to settle down on that example or not, since there is room for interpretation there.  You could also think in terms of Plane extending Vehicle and FlyingObject and Bird extending Animal and FlyingObject, or in terms of a much purer example.

答:
For quite a while now it never really occurred to me how totally different some programming tasks are from others--and how much it helps if the languages and patterns used are tailored to the problem space.

When you are working alone or mostly isolated on code that you wrote it's a completely different problem space from inheriting a codebase from 40 people in India who worked on it for a year before handing it to you without any transitional help.

Imagine you were just hired by your dream company and then inherited such a code base.  Furthermore imagine that the consultants had been learning about (and therefore infatuated with) inheritance and multiple-inheritance...  Could you picture what you might be working on.

When you inherit code the most important feature is that it is understandable and the pieces are isolated so they can be worked on independently.  Sure when you are first writing the code structures like multiple inheritance might save you a little duplication and seem to fit your logical mood at the time, but the next guy just has more stuff to untangle.

Every interconnection in your code also makes it more difficult to understand and modify pieces independently, doubly so with multiple inheritance.

When you are working as part of a team you want to target the simplest possible code that gives you absolutely no redundant logic (That's what DRY really means, not that you shouldn't type much just that you never have to change your code in 2 places to solve a problem!)

There are simpler ways to achieve DRY code than Multiple Inheritance, so including it in a language can only open you up to problems inserted by others who might not be at the same level of understanding as you are.  It's only even tempting if your language is incapable of offering you a simple/less complex way to keep your code DRY.


问:
Interpreter or virtual machine that does not execute bytecode
The developers of the Dart language tell that there is a virtual machine that executes statements written in Dart language. What is the difference between an interpreter and a virtual machine that executes a language?

Until now the virtual machines that I knew, like Java Virtual Machine, Common Language Runtime, and Dalvik all execute bytecode that has been previously compiled from a programming language.

How does it work a virual machine that executes directly a programming language?

答:
And how do you think the bytecode got created? Most probably something read the statements written in a language and converted it to bytecode. For example Java and C# compilers both do this.

Dart VM just skips this step and reads the statements directly. It is actually quite common for interpreted languages to do that. For example JavaScript and PHP were both like this before it became necessary to improve performance, and add the bytecode-generation step into the runtime process.


答: It probably works just as a normal Virtual Machine just instead of translating bytecode into machine code it translates the language into machine code. This might be different from an interpreter by having a JIT compiler which starts to compile the code into machine language and keeps this code to be run while an interpreter translates into machine code each time an instruction is executed.</p>

Title: Interpreter or virtual machine that does not execute bytecode

Body:
The developers of the Dart language tell that there is a virtual machine that executes statements written in Dart language. What is the difference between an interpreter and a virtual machine that executes a language?

Until now the virtual machines that I knew, like Java Virtual Machine, Common Language Runtime, and Dalvik all execute bytecode that has been previously compiled from a programming language.

How does it work a virual machine that executes directly a programming language?


问:
iOS7 apps only using iPad only
I would like to develop iOS apps but due to budgetary issues I can only afford an iPad mini gen1 or iPod touch 5th gen. Is it possible for me to make apps for all iPhones and iPads/iPods using just a single device? Another question is how does the latest iOS7 work on ipad mini gen 1/iPod touch and what are the limitations when working with these devices when compared to an iPhone(My target apps are trivia and endless runner games).

Thanks

P.S. I do have a mac with xcode on it and I am developing a cocoa app right now and the question is if i can develop for all io7 devices using just one deceive for final testing.

答:
Absolutely. As long as you have a developer certificate and a provisioning profile, you can simulate any device on Xcode runbing any version of iOS. You will also be able to use the iPad mini to test on a device. Bear in mind that iPod touches can't upgrade to iOS 7.
It's also worth noting that when designing multi sized apps spanning retina and standard resolutions, you will have to carefully consider auto layout along with different asset image sizes including rotations</p>

Title: iOS7 apps only using iPad only


答:
The concept of "prototyping", as intended in RAD, is a bit foreign to agile development. This doesn't mean it can't be done, but it's unusual.

There are different cases that need to be explored:

Is the prototype an "empty shell", a mock up or a demo, built to give an idea on how a product would look like? You can certainly do it with one or more stories -- however you are building something out of your own imagination, not building a product out of real feedback. People don't evaluate a demo like they evaluate a product. For example see the feedback about our top bar prototype versus our real top bar implementation.

Is the prototype something that needs to be built in order to understand better the problem space? Then it should be covered as a spike, and only its results kept (source code is transient).

Is the prototype a version 0.x? A mininimum viable product? Then use the agile process of your choice for it. If you need to rebuild it in another language, you are likely to be better off if you treat that a different product. Note that sometimes this is treated as a way of shortcutting writing a spec ("it should do the same as the prototype!"). That's a really poor way of documenting a product, but this is probably better explained as a separate question and answer :-)


答:
For composite conditions, you could consider to take into account the fact that, in Java, conditions evaluation is lazy. That means that the program will only evaluate the (sub)conditions until it can decide if the conditional statements must be executed or not.

So, for instance, if you have two conditions c1 and c2, and if c1 can be quickly evaluated since c2 take a while to be evaluated, prefer if(c1 and/or c2) to if(c2 and/or c1), so that you could more quickly determine if the global condition is respected or not. Similarly, prefer

```<code>if(c1){
   if(c2){
      (...)
   }
}
</code>```

to

```<code>if(c2){
   if(c1){
      (...)
   }
}
</code>```

In the worse case it does not change anything, and in the best case you spare a test.

This is a general principle, you can also consider the fact that one of the conditions will be true virtually all the times. In that case, it could be interesting to place it first in a OR composition, so that you will virtually never test the second condition. It becomes harder to decide how to order the conditions when you have to consider simultaneously time consumption and value probability.

Be aware that before changing the order of your conditions, you must be sure they imply no side effect, otherwise a reordering may change the behaviour of your program.

Title: Ordering if conditions for efficiency and clean code

Body:
This is purely a design question and the example is simple to illustrate what I am asking and there are too many permutations of more complex code to provide examples that would cover the topic. I am not referring specifically to this example, just using the example to illustrate what I am referring to.

In an if statement, is there a preferred way to order conditions, in terms of coding convention and, more importantly, efficiency?

For such a simple example, efficiency will not be an issue, but I am not asking for a code review per se, but an understanding of the concept.

Two alternatives:

1.

```<code>public double myStuff(int i)
{
    // check for an invalid number of tourists
    if (i > 0)
    {
        // do something here

        return doubleSomething;
    } else
    {
        return Double.NaN;
    }
}
</code>```

2.

```<code>public double myStuff(int i)
{

    if (i <= 0)
    {
        return Double.NaN;

    } else
    {

        {
            // do something here

            return doubleSomething;
        }
</code>```

If the if statement was to become more complex, and possibly nested, in what order should conditions be addressed?

Body:
For composite conditions, you could consider to take into account the fact that, in Java, conditions evaluation is lazy. That means that the program will only evaluate the (sub)conditions until it can decide if the conditional statements must be executed or not.

So, for instance, if you have two conditions c1 and c2, and if c1 can be quickly evaluated since c2 take a while to be evaluated, prefer if(c1 and/or c2) to if(c2 and/or c1), so that you could more quickly determine if the global condition is respected or not. Similarly, prefer

if(c1){
   if(c2){
      (...)
   }
}

to

if(c2){
   if(c1){
      (...)
   }
}

In the worse case it does not change anything, and in the best case you spare a test.

This is a general principle, you can also consider the fact that one of the conditions will be true virtually all the times. In that case, it could be interesting to place it first in a OR composition, so that you will virtually never test the second condition. It becomes harder to decide how to order the conditions when you have to consider simultaneously time consumption and value probability.

Be aware that before changing the order of your conditions, you must be sure they imply no side effect, otherwise a reordering may change the behaviour of your program.


问:
What does SVN do better than Git?
No question that the majority of debates over programmer tools distill to either personal choice (by the user) or design emphasis, that is, optimizing design according to particular uses cases (by the tool builder). Text editors are probably the most prominent example--a coder who works on Windows at work and codes in Haskell on the Mac at home, values cross-platform and compiler integration and so chooses Emacs over TextMate, etc.

It's less common that a newly introduced technology is genuinely, demonstrably superior to the extant options.

Is this in fact the case with version-control systems (VCS), in particular, centralized VCS (CVS and SVN) versus distributed VCS (Git and Mercurial)?

I used SVN for about five years, and SVN is currently used where I work. A little less than three years ago, I switched to Git (and GitHub) for all of my personal projects.

I can think of a number of advantages of Git over Subversion (and which for the most part abstract to advantages of distributed over centralized VCS), but I cannot think of one contra example--some task (that's relevant and arises in a programmers usual workflow) that Subversion does better than Git.

The only conclusion I have drawn from this is that I don't have any data--not that Git is better, etc.

My guess is that such counter-examples exist, hence this question.

答:
Sense of security when doing an 'svn commit'. Since commits go to the server, there's no possible screwup that I can do that will erase my changes after they are committed. In git, commits are local, so until I push, a stray 'rm -rf' and it's all over.

Commits are authenticated. By default in git I can tell it I'm committing as anyone.

Fewer commands to learn for everyday use. 'svn checkout', 'svn up', and 'svn commit' will get you pretty far.

Shared checkouts work a lot nicer. When you go to commit, it asks you for your username/password, you don't have to remember to pass certain command line arguments. Sometimes at work we have a shared machine with a shared svn checkout of some project. Someone might say "Bob can you look at this on this machine" and he can, and he can commit his changes as his user without any screw ups.

Repository layout. You can have an umbrella project and subprojects and choose what to check out when.

Revision numbers are incrementing integers.

Designed for the central repository workflow.

Title: What does SVN do better than Git?


问:
Layered Manufacturing Contour Generation
I am currently working on software for layered manufacturing (3D printing), and have come to a point where I no longer know what to do. I am at the stage where I must take a bunch of lines, and order them to create a seamless contour of a model. I have some basic ideas on how I am going to do this, but since I am using .STL files there are excess lines in some of the layers.

In that image you can see that there is a simple square with a line connecting two corners to form two triangles. This is the base of a cube. Ideally the line connecting the two corners wouldn't be there, but because this was processed from a .STL file which uses triangles only it has to be there to turn the square into two triangles. My original thought was to print out that line too, but in a more complex model ( like a gear ) there would be too many and it would be impossible to create one seamless contour. My next thought was to just print it out as two triangles, but I cannot go over the same line twice, so that doesn't work especially in complex models. I have been thinking about this problem for quite a while, but I can never come up with a solution that would work for any model. I need to end up with series of lines that form contours of not just the outside, but possibly the inside as well if there are holes. For example a gear would have one set of lines that form the teeth all the way around, and another set of lines that form the hole in the middle. If anyone knows a solution to this, or has experience with this, I would greatly appreciate your input =)

答:
I don't know about STL specifically, but i've seen some other languages with some rules to 'remove' parts.

Even-odd rule:  Only draw lines that are present an odd number of times.

Non-zero sum: If there's a line form A to B, and then another from B to A, the second one 'substracts' from the first and the sum is zero, so ignore it.  But if there's to A-B and one B-A, or one A-B and two B-A, then the sum is not zero, so you have to draw it.

Note that in both cases you have to determine if the second line is the same line or points, not "very close".  That's easier if the format first defines the points and then the lines or polygons that use them.  In STL you would have to choose if you consider 'same' points only if they're textually identical, or if you'll define a margin of similarity.


问:
DevOps versus Software Engineers
I am aware that all the DevOps definitions are fairly vague, and this question is subjective, but it's still something I couldn't find an answer to.

Is there any difference, prestige-wise, between DevOps and Software Engineers? Is the experience interchangeable? Are N years of DevOps experience interchangeable for N years of software engineering experience?

Or do I even view the question in the wrong light?

答:
I don't DevOps and Software Engineers can be directly compared.

Software Engineer is job title, and doesn't tell you very much about the type of projects you'll be working on.

DevOps is a type of project, and doesn't really say much about what position someone works in.

It's very possible to be a Software Engineer working on DevOps projects, or if you work for a company that creates DevOps tools, you could work "in DevOps" as a market annalist.

Title: DevOps versus Software Engineers


答: As you rightly said DevOps is vague term, therefore it depends on the "implementation". In companies that drive DevOps as a culture, the Software Engineer becomes a DevOp. Other companies/organisation have special DevOps teams (e.g., CERN) whose tasks are a mixture of classical IT administration and software development.</p>

Title: DevOps versus Software Engineers

Body:
I am aware that all the DevOps definitions are fairly vague, and this question is subjective, but it's still something I couldn't find an answer to.

Is there any difference, prestige-wise, between DevOps and Software Engineers? Is the experience interchangeable? Are N years of DevOps experience interchangeable for N years of software engineering experience?

Or do I even view the question in the wrong light?


问:
Text Adventure language
I was thinking of creating a text adventure game and after a small google search, I found out that quite a few (simple) text adventure games are created in Prolog.

Why is that?

答:
From Exploring Prolog:

As I was writing the utility functions for my game, I happened to go to a Boston Computer Society meeting where the speaker was discussing Prolog. I learned that all of the tools I was building were already integral components of the Prolog language.

Prolog has built-in dynamic memory allocation for storing the state of
the game that was better than mine because it had an extremely
flexible way of representing the data. It has a built-in
pattern-matching capability (unification) that was more general and
flexible than the pattern-matcher I was implementing, and it had a
built-in search mechanism (backtracking). Further, the dynamic memory
allocation didn't just store facts, but stored rules as well, so the
"data" could embody its own intelligence.

Because of all of this procedural power built into the language, the
code the programmer writes looks much more declarative. An
application, such as my adventure game, winds up being reduced to an
elegant set of logical declarations describing what the program does.
(Developers often claim up to a 10-fold reduction in code size going
to Prolog. See for example the PCAI article on KnowledgeWare's use of
Prolog in the May/June 1993 issue.) For me, this was truly a fun way
to program, capturing the essence of the joy of programming-building
logical structures that perform interesting tasks.

Title: Text Adventure language


答: The 1K (not a typo) Basic for the earliest home computers, and their beefier descendents, worked by interpreting directly from the source code.  Bill Gates was no slouch!</p>


问:
How could Clang release under BSD license?
I found that llvm could only generate assembly code. If someone want generate and link assembly code to native executable code, they should use external tool(GNU as/ld, for example. Currently lld is not ready, and there no more information about llvm-mc).

This question's answer and other answers imply that Clang use Binutils(as and ld) to generate and link native code(I'm not quite sure about this). If so, how could Clang release  under BSD like license? I can't find any license exception(like Bison Exception) about ld or as.

If I misunderstand some concepts, please forgive me! BTW, could we use GNU as and ld in programmatically way?

EDIT: Thanks for these answers. It seems that clang still not a standalone toolchain and have to use VS or GNU tools. Does it mean if someone write a compiler based on llvm. If users didn't install GNU or VS tools. The compiler is not a out-of-the-box compiler?

答:
AFAIK (though I am not a lawyer), running a GPL'd application from the command line or similar does not count as derivative work.
Aside from that, the LLD subproject is creating a similarly-licensed linker. Although I don't think it's used by Clang yet.</p>


问:
Storing a pass-by-reference parameter as a pointer - Bad practice?
I recently came across the following pattern in an API I've been forced to use:

```<code>class SomeObject
{
public:
    // Constructor.
    SomeObject(bool copy = false);

    // Set a value.
    void SetValue(const ComplexType &value);

private:
    bool         m_copy;
    ComplexType *m_pComplexType;
    ComplexType  m_complexType;
};

// ------------------------------------------------------------

SomeObject::SomeObject(bool copy) :
  m_copy(copy)
{
}

// ------------------------------------------------------------

void SomeObject::SetValue(const ComplexType &value)
{
    if (m_copy)
        m_complexType.assign(value);
    else
        m_pComplexType = const_cast<ComplexType *>(&value);
}
</code>```

The background behind this pattern is that it is used to hold data prior to it being encoded and sent to a TCP socket. The copy weirdness is designed to make the class SomeObject efficient by only holding a pointer to the object until it needs to be encoded, but also provide the option to copy values if the lifetime of the SomeObject exceeds the lifetime of a ComplexType.

However, consider the following:

```<code>SomeObject SomeFunction()
{
    ComplexType complexTypeInstance(1);  // Create an instance of ComplexType.

    SomeObject encodeHelper;
    encodeHelper.SetValue(complexTypeInstance); // Okay.

    return encodeHelper;

    // Uh oh! complexTypeInstance has been destroyed, and
    // now encoding will venture into the realm of undefined
    // behaviour!
}
</code>```

I tripped over this because I used the default constructor, and this resulted in messages being encoded as blank (through a fluke of undefined behaviour). It took an absolute age to pinpoint the cause!

Anyway, is this a standard pattern for something like this? Are there any advantages to doing it this way vs overloading the SetValue method to accept a pointer that I'm missing?

Thanks!

答:
Another solution would be to replace the method that takes a reference with one that takes a pointer. The caller would then create the object using the new operator and store it in a unique_ptr (I would say auto_ptr, but the very reason it was deprecated is what we would end up using here). That way, you neither make copies, nor worry about destruction of the object.

A quick mash-up would be

```<code>class SomeObject
{
public:
    // Constructor.
    SomeObject();

    // Set a value.
    void SetValue(unique_ptr<ComplexType> pValue);

private:
    std::unique_ptr<ComplexType> m_pComplexType;
};

// ------------------------------------------------------------

void SomeObject::SetValue(std::unique_ptr<ComplexType> pValue)
{
    m_pComplexType = std::move(pValue);
}
</code>```

.. which can be used as:

```<code>SomeObject SomeFunction()
{
    std::unique_ptr<ComplexType> pobjComplexTypeInstance= new ComplexType(1);  // Create an instance of ComplexType and store it in a unique_ptr

    SomeObject encodeHelper;
    encodeHelper.SetValue(pobjComplexTypeInstance); // Pass the unique_ptr, it will be copied inside the function

    return encodeHelper;
}
</code>```

Body:
Another solution would be to replace the method that takes a reference with one that takes a pointer. The caller would then create the object using the new operator and store it in a unique_ptr (I would say auto_ptr, but the very reason it was deprecated is what we would end up using here). That way, you neither make copies, nor worry about destruction of the object.

A quick mash-up would be

class SomeObject
{
public:
    // Constructor.
    SomeObject();

    // Set a value.
    void SetValue(unique_ptr<ComplexType> pValue);

private:
    std::unique_ptr<ComplexType> m_pComplexType;
};

// ------------------------------------------------------------

void SomeObject::SetValue(std::unique_ptr<ComplexType> pValue)
{
    m_pComplexType = std::move(pValue);
}

.. which can be used as:

SomeObject SomeFunction()
{
    std::unique_ptr<ComplexType> pobjComplexTypeInstance= new ComplexType(1);  // Create an instance of ComplexType and store it in a unique_ptr

    SomeObject encodeHelper;
    encodeHelper.SetValue(pobjComplexTypeInstance); // Pass the unique_ptr, it will be copied inside the function

    return encodeHelper;
}