答:
I did it a couple of times.  What was common was that the client didn't really knew what they wanted, so i wrote the specs :-)

Well, in fact one of them was "we need something to manage our image library", so i knew they needed a DAM.  just a few questions more to get their workflow, and then I was free to write one to fit that.

The second time was after a first quick version of a system where we got very positive reviews on everything except a single feature that was admittedly very crude (because we had to deliver quickly the first version). I just closed my door and promised the next version would fix that.  Since we already knew that part wasn't good we had planned for the second version and could focus on that part of the code, knowing the rest was (almost) ready for the enhancement.

Title: Software on Budget and on time?

Body:
We've all (almost all) have heard about the horror stories as well as perhaps studied about them.

Its easy to find stories of software that is over budget and late.

I wanted to hear from developers the opposite story:

Question:

Do you know, or have worked on a project that was on budget and on time?

What is the most valuable lesson you learned from it?


问:
Is this how dynamic language copes with dynamic requirement?
The question is in the title. I want to have my thinking verified by experienced people. You can add more or disregard my opinion, but give me a reason.

Here is an example requirement: Suppose you are required to implement a fighting game. Initially, the game only includes fighters, who can attack each other. Each fighter can punch, kick or block incoming attacks. Fighters can have various fighting styles: Karate, Judo, Kung Fu... That's it for the simple universe of the game. In an OO like Java, it can be implemented similar to this way:

```<code>abstract class Fighter {
    int hp, attack;

    void punch(Fighter otherFighter);
    void kick(Fighter otherFighter);
    void block(Figther otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };
</code>```

This is fine if the game stays like this forever. But, somehow the game designers decide to change the theme of the game: instead of a simple fighting game, the game evolves to become a RPG, in which characters can not only fight but perform other activities, i.e. the character can be a priest, an accountant, a scientist etc... At this point, to make it more generic, we have to change the structure of our original design: Fighter is not used to refer to a person anymore; it refers to a profession. The specialized classes of Fighter (KaraterFighter, JudoFighter, KungFuFighter) . Now we have to create a generic class named Person. However, to adapt this change, I have to change the method signatures of the original operations:

```<code>class Person {
    int hp, attack;
    List<Profession> skillSet;
};

abstract class Profession {};

class Fighter extends Profession {
    void punch(Person otherFighter);
    void kick(Person otherFighter);
    void block(Person otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };

class Accountant extends Profession {
     void calculateTax(Person p) { //...implementation...};
     void calculateTax(Company c) { //...implementation...};
};
//... more professions...
</code>```

Here are the problems:

To adapt to the method changes, I have to fix the places where the changed methods are called (refactoring).

Every time a new requirement is introduced, the current structural design has to be broken to adapt the changes. This leads to the first problem.

Rigid structure makes it hard for code reuse. A function can only accept the predefined types, but it cannot accept future unknown types. A written function is bound to its current universe and has no way to accommodate to the new types, without modifications or rewrite from scratch. I see Java has a lot of deprecated methods.

OO is an extreme case because it has inheritance to add up the complexity, but in general for statically typed language, types are very strict.

In contrast, a dynamic language can handle the above case as follow:

```<code>;;fighter1 punch fighter2
(defun perform-punch (fighter1 fighter2) ...implementation... )

;;fighter1 kick fighter2
(defun perform-kick (fighter1 fighter2) ...implementation... )

;;fighter1 blocks attacks from fighter2
(defun perform-block (fighter1 fighter2) ...implementation... )
</code>```

fighter1 and fighter2 can be anything as long as it has the required data for calculation; or methods (duck typing). You don't have to change from the type Fighter to Person. In the case of Lisp, because Lisp only has a single data structure: list, it's even easier to adapt to changes. However, other dynamic languages can have similar behaviors as well.

I work primarily with static languages (mainly C and Java, but working with Java was a long time ago). I started learning Lisp and some other dynamic languages this year. I can see how it helps improving my productivity.

答:
I think the answer boils down to:  yes a "dynamic" language helps your coding productivity as you can make sweeping changes quickly and easily. However, it hurts your release productivity as you have create a mess of code that has no consistent structure to it and lots of only-runtime-detectable errors that will need fixing later, rather than sooner like you'd get in a "static" language.

There's simply no substitute for doing things correctly, and that means thought, design, and careful consideration of the impact of your changes.

ContentLicense: CC BY-SA 3.0


问:
Examples of Java APIs that demand an action sequence
As part of a research I'm working on, I'm looking for public APIs that only work correctly when you apply a certain sequence of actions on them.

For example, the java.nio.channels.SocketChannel class, from the Java standard library, only works correctly with sequences such as open() -> connect() -> read() -> read() -> close(). A more complete demonstration if how it may be used may be represented in the following graph:

Additional examples of Java standard library APIs that require certain sequences are java.io.PrintStream (very similar to the one above) and java.util.Iterator (which requires a next() call between every two remove() calls, thus enforcing a certain sequence).

So, does you favorite API for doing X also behave that way? I would very much like to know about additional APIs that require a certain method sequence for correct usage; especially classes that are not part of the Java standard library. The more complex the sequence(s) required, the better.

Some APIs require a sequence that spans across multiple classes, for example:

```<code>X x = new X();
x.setup();
Y y = x.createNewY();
Z z = new Z(y);
z.doSomething();
</code>```

These examples are also interesting, but I'm mostly looking for sequences that all appear in the same class.

EDIT added bounty for greater visibility. I'm sure many of you have encountered many APIs that will match this description - I would really appreciate some good examples.

答:
What about the java.util.Calendar? It doesn't require a complcated action sequence, but it's a real PITA for the number of times you need to use it:

```<code>//1. get a new instance
Calendar cal=Calendar.getInstance();
//2. set the different fields
cal.set(Calendar.DATE, 12);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.YEAR, 1982);
//3. use it, for whatever
Date d=cal.getTime();
</code>```

And, not to talk about the Java Transaction API, when Bean managed:

```<code>@Stateless
@TransactionManagement(BEAN)
public class ExampleBean {

    @Resource
    private SessionContext ctx;

    public void foo() {
        UserTransaction utx = ctx.getUserTransaction();

        // start a transaction
        utx.begin();

        // Do work

        // Commit it
        utx.commit();
    }
}
</code>```

The JAXB marshalling

```<code>//1. get context
JAXBContext jc = JAXBContext.newInstance( Foo.class );
//2. create Marshaller instance
Marshaller m = jc.createMarshaller();
//3. set properties
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
  Boolean.TRUE);
//at last, marshall
m.marshal( foo, System.out );
</code>```

and unmarshalling:

```<code>//1. get context
JAXBContext jc = JAXBContext.newInstance( Foo.class );
//2. create Unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();
//3. optional: set properties, format validation, schema validation, etc
u.setValidating( true );
//4. unmarshall
Foo foo = (PurchaseOrder)u.unmarshal(
       new FileInputStream( "po.xml" ) );
</code>```

ContentLicense: CC BY-SA 2.5

Body:
What about the java.util.Calendar? It doesn't require a complcated action sequence, but it's a real PITA for the number of times you need to use it:

//1. get a new instance
Calendar cal=Calendar.getInstance();
//2. set the different fields
cal.set(Calendar.DATE, 12);
cal.set(Calendar.MONTH, Calendar.JANUARY);
cal.set(Calendar.YEAR, 1982);
//3. use it, for whatever
Date d=cal.getTime();

And, not to talk about the Java Transaction API, when Bean managed:

@Stateless
@TransactionManagement(BEAN)
public class ExampleBean {

    @Resource
    private SessionContext ctx;

    public void foo() {
        UserTransaction utx = ctx.getUserTransaction();

        // start a transaction
        utx.begin();

        // Do work

        // Commit it
        utx.commit();
    }
}

The JAXB marshalling

//1. get context
JAXBContext jc = JAXBContext.newInstance( Foo.class );
//2. create Marshaller instance
Marshaller m = jc.createMarshaller();
//3. set properties
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
  Boolean.TRUE);
//at last, marshall
m.marshal( foo, System.out );

and unmarshalling:

//1. get context
JAXBContext jc = JAXBContext.newInstance( Foo.class );
//2. create Unmarshaller instance
Unmarshaller u = jc.createUnmarshaller();
//3. optional: set properties, format validation, schema validation, etc
u.setValidating( true );
//4. unmarshall
Foo foo = (PurchaseOrder)u.unmarshal(
       new FileInputStream( "po.xml" ) );


问:
How to properly use Hibernate
I am new to Hibernate so my question could be seen as a very straight forward one, also I will try not to be too generic (as I am always told off because of that), although as with all architectural question it is hard to avoid that... I never know where to ask these questions.

I have setup a webapp using Spring + Hibernate. My architecture uses a series of Controllers which make use of Services that ultimately call DAO methods to obtain my domain objects.

I also have a GenericDAO which implements all the basic data access methods (findAll, findById, save, delete, update...) which I extend for my concrete Dao so I only have to implement specific data access methods.

So a request to view all users will have this flow: the proper controller is called through request mapping, which feeds the view with the result from calling userService.getAllUsers() which at the same time makes a call to userDao.findAll().

This is all nice and I think I'm doing it properly enough.

My question relates to relationships among domain objects, so let's say users have accounts and for one view I want to show the user's details plus his list of accounts.

I never found out what's the best way to gather the accounts object list. Should I mark the relationship as Eager? Should I make a call like this:

```<code>user.accountList = accountService.findAccountsByUser(userId);
</code>```

if that's the case then what's the point of specifying the relationship in the first place? Or maybe I am missing some other way here?

What happens with Many to Many relationships? Am I forced to create a domain object called UserAccount (assuming an account can be associated to several users) that maps the relations between the two?

答:
You can also control the "eager/lazy" fetching at query time. From the docs:

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-joins

A "fetch" join allows associations or collections of values to be
  initialized along with their parent objects using a single select.
  This is particularly useful in the case of a collection. It
  effectively overrides the outer join and lazy declarations of the
  mapping file for associations and collections.

I think the more specific question you want to ask here is: how do I avoid loading too many objects (more than necessary for a given situation) but at the same time, when I do want to load them all, how do I avoid the dredded N+1 select issue

A rule of the thumb can be the following: what's the most often used fashion to get X data for my application? Do I mostly need it with its sub-entities populated or do I only seldom need those as well. This rule should guide you into setting eager/lazy fetching on the association. Then for those non-standard cases where you need data in a fashion different from the declared eager or lazy relationship-level annotation, you can override it using the above mentioned query-level fetch join.

A good way to double check all this is to debug Hibernate at the generated SQL level. For example this can quickly show you if a certain (single) Hibernate query becomes a series of (N+1) selects when getting translated to SQL. Here's a good article on how to configure this:

http://www.mkyong.com/hibernate/hibernate-display-generated-sql-to-console-show_sql-format_sql-and-use_sql_comments/

Title: How to properly use Hibernate


问:
Reducing Coupling in a Series of Tasks
I am working on some code right now that involves processing user requests. Each request requires going through an approval. When a request is made, one or more records are created on the database recording what the request entails. Then a ticket is created and placed on the approver's work queue.

For a typical request, approving it involves these steps:

The request is processed (usually resulting in a table getting updated)

The changes are recorded to a history table (record auditing).

The request is marked as approved by the approver (approval auditing).

The ticket is removed from the work queue.

The original requester is sent an email telling them their request was approved.

We have a single class that kicks off these steps sequentially within a transaction (http://martinfowler.com/eaaCatalog/transactionScript.html). For the most part, the sequence doesn't really matter and the email isn't really essential.

The problem is each of these classes has at least 5+ dependencies (in reality, it's closer to 10+). I am stumped about how to reduce the number of dependencies when it comes to a workflow like this.

I thought about grouping some of these items together, but there's no logical grouping. I don't see much of a point in creating an unnecessary layer like that, anyway.

I also thought about doing some kind of observer pattern (.NET events). A class higher up could listen for the event, instantiate the needed classes and kick them off. However, that "higher-up class" would then be dependent on all of the classes again, so I'd be right back in the same situation.

So, the only ways I've been able to think of reducing the number of dependencies is to either do artificial grouping of classes or to just make it the layer above's problem. Neither seem ideal and I wonder if I am missing something. If it helps, I am using Ninject with ASP.NET MVC. I have access to an IOC container (DependencyResolver). I am wondering if the solution is some sort of combination between using listeners/events and an IOC container.

答:
If you're calling these steps, then clearly the order is relevant to some degree. The exact order may not matter, but there is going to be a certain amount of "X and Y happen before Z". For example, you probably don't want to send the email saying the request was approved, before it has actually been approved. Likewise, the request probably cannot be approved before it is actually processed/added to the queue/etc.

Transaction scripts (or "workflow managers") are basically procedural code. The number of dependencies isn't really the issue, it's just a proxy for the issue. The actual issue is the number of responsibilities the script has. And in your case, the number of responsibilities grows with each new step you add. And that, of course, goes against the Single Responsibility Principle.

The most common antithesis to procedural code is event-driven code. You say this:

A class higher up could listen for the event, instantiate the needed classes and kick them off. However, that "higher-up class" would then be dependent on all of the classes again, so I'd be right back in the same situation.

But that's missing the point. You're still trying to have one class that's responsible for every step. Instead, you want to have a class for each step - it listens for whatever precursor events are supposed to trigger that step, and then starts that step and that step alone. One responsibility, and very few dependencies, since the events themselves are just small bags of "arguments", or in some cases just strings or marker interfaces.

There are lots of frameworks around to coordinate the event handlers, ranging from highly-reliable, transactional service buses like NServiceBus or Mass Transit, which are heavy on infrastructure and designed for distributed systems, all the way to Appcelerate (formerly bbvCommom/bbvEventBroker, which has a Ninject extension) or Udi Dahan's simple Domain Events implementation, which are designed to run entirely in-process.

The basic idea is always the same, though:

A client sends a message to initiate some process.

A handler (or several) responds to that message.

Each handler publishes some event whenever it is finished.

Subsequent handlers may respond to those events and continue the process.

This goes on for as long as it has to, until there is no longer anything "listening".

So, in your example, you might have these classes (note: this is not written to be specific to any particular framework, it's more or less pseudocode):

```<code>// Messages
public class SubmitOrderCommand { ... }
public class ApproveOrderCommand { ... }
public class OrderProcessedEvent { ... }
public class OrderApprovedEvent { ... }

// Handlers
public class OrderProcessor : IConsume<SubmitOrderCommand>
{
    public void Handle(SubmitOrderCommand message)
    {
        // Process the order
        Events.Publish<OrderProcessedEvent>();
    }
}

public class OrderAuditor : IConsume<OrderCommand>, IConsume<OrderProcessedEvent>
{
    public void Handle(OrderCommand message) { // Write to audit log }
    public void Handle(OrderProcessedEvent message) { // Mark order as processed }
}

public class OrderApprover : IConsume<OrderProcessedEvent>, IConsume<ApproveOrderCommand>
{
    public void Handle(OrderProcessedEvent message)
    {
        // Notify somebody that an order needs to be approved
    }

    public void Handle(ApproveOrderCommand message)
    {
        // Remove ticket from work queue
        Events.Publish<OrderApprovedEvent>();
    }
}

public class OrderNotifier : IConsume<OrderApprovedEvent>
{
    public void Handle(OrderApprovedEvent message) { // Send an email }
}
</code>```

I assume you get the idea. In this architecture, the number of dependencies for each handler is entirely limited to the actions that it is directly responsible for, and the one or two events that it consumes or publishes.

Of course, this means giving up the security blanket of having the entire workflow described in one place. Managers and business analysts really love their flow charts, and even programmers tend to get attached to the ability to see, at a glance, every step that's involved in a particular process. The practical upside to the event-driven model is much looser coupling, testability, and the ability to expand the workflow "horizontally" without changing any existing handlers, or actually needing to understand or care about the exact order of events.

P.S. All of the frameworks I mentioned perform dependency injection on the handlers. You don't instantiate the handlers, the framework does. That's what makes this so different from a transaction script.

Title: Reducing Coupling in a Series of Tasks

Body:
If you're calling these steps, then clearly the order is relevant to some degree. The exact order may not matter, but there is going to be a certain amount of "X and Y happen before Z". For example, you probably don't want to send the email saying the request was approved, before it has actually been approved. Likewise, the request probably cannot be approved before it is actually processed/added to the queue/etc.

Transaction scripts (or "workflow managers") are basically procedural code. The number of dependencies isn't really the issue, it's just a proxy for the issue. The actual issue is the number of responsibilities the script has. And in your case, the number of responsibilities grows with each new step you add. And that, of course, goes against the Single Responsibility Principle.

The most common antithesis to procedural code is event-driven code. You say this:

A class higher up could listen for the event, instantiate the needed classes and kick them off. However, that "higher-up class" would then be dependent on all of the classes again, so I'd be right back in the same situation.

But that's missing the point. You're still trying to have one class that's responsible for every step. Instead, you want to have a class for each step - it listens for whatever precursor events are supposed to trigger that step, and then starts that step and that step alone. One responsibility, and very few dependencies, since the events themselves are just small bags of "arguments", or in some cases just strings or marker interfaces.

There are lots of frameworks around to coordinate the event handlers, ranging from highly-reliable, transactional service buses like NServiceBus or Mass Transit, which are heavy on infrastructure and designed for distributed systems, all the way to Appcelerate (formerly bbvCommom/bbvEventBroker, which has a Ninject extension) or Udi Dahan's simple Domain Events implementation, which are designed to run entirely in-process.

The basic idea is always the same, though:

A client sends a message to initiate some process.

A handler (or several) responds to that message.

Each handler publishes some event whenever it is finished.

Subsequent handlers may respond to those events and continue the process.

This goes on for as long as it has to, until there is no longer anything "listening".

So, in your example, you might have these classes (note: this is not written to be specific to any particular framework, it's more or less pseudocode):

// Messages
public class SubmitOrderCommand { ... }
public class ApproveOrderCommand { ... }
public class OrderProcessedEvent { ... }
public class OrderApprovedEvent { ... }

// Handlers
public class OrderProcessor : IConsume<SubmitOrderCommand>
{
    public void Handle(SubmitOrderCommand message)
    {
        // Process the order
        Events.Publish<OrderProcessedEvent>();
    }
}

public class OrderAuditor : IConsume<OrderCommand>, IConsume<OrderProcessedEvent>
{
    public void Handle(OrderCommand message) { // Write to audit log }
    public void Handle(OrderProcessedEvent message) { // Mark order as processed }
}

public class OrderApprover : IConsume<OrderProcessedEvent>, IConsume<ApproveOrderCommand>
{
    public void Handle(OrderProcessedEvent message)
    {
        // Notify somebody that an order needs to be approved
    }

    public void Handle(ApproveOrderCommand message)
    {
        // Remove ticket from work queue
        Events.Publish<OrderApprovedEvent>();
    }
}

public class OrderNotifier : IConsume<OrderApprovedEvent>
{
    public void Handle(OrderApprovedEvent message) { // Send an email }
}

I assume you get the idea. In this architecture, the number of dependencies for each handler is entirely limited to the actions that it is directly responsible for, and the one or two events that it consumes or publishes.

Of course, this means giving up the security blanket of having the entire workflow described in one place. Managers and business analysts really love their flow charts, and even programmers tend to get attached to the ability to see, at a glance, every step that's involved in a particular process. The practical upside to the event-driven model is much looser coupling, testability, and the ability to expand the workflow "horizontally" without changing any existing handlers, or actually needing to understand or care about the exact order of events.

P.S. All of the frameworks I mentioned perform dependency injection on the handlers. You don't instantiate the handlers, the framework does. That's what makes this so different from a transaction script.


问:
Advice on which storage technology for an Image repository
At this point, I'm not much of a programmer, solid html/css, familiar with JS but not a programmer by any means. I'm looking to pick up whatever is necessary for an upcoming project.

I need to build an online image repository that will host around 15k photos. Those photos will need to have user entered data associated with them. They will need to be searchable by tags, and batch downloadable.

Would you guys do filesystem or db storage?  Basically, what type of storage solution would you use?

答:
Storing files in the filesystem is surely a good quick solution which works and I personally would never suggest to store files in a database not even on those rare occasions in which it could be done.

On another note however consider that storing files in the filesystem directly from a web applications is generally not the clean solution.

In some frameworks for instance it breaks common guidelines, see for instance the JavaEE guidelines here: http://www.oracle.com/technetwork/java/restrictions-142267.html, in this case your are breaking the Server model if you "create, modify, or delete files in the filesystem".

This because storing files directly in the filesystem is not scalable to the cloud where servers could be running in different virtual machines across dozens of hard disks.

In Java the suggested solution would be using a standard container like Apache JackRabbit.


问:
Is it a bad idea to return different data types from a single function in a dynamically typed language?
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.

答:
Actually, it's not very uncommon at all to return different types even in a statically typed language. That's why we have union types, for example.

In fact, methods in Java almost always return one of four types: some kind of object or null or an exception or they never return at all.

In many languages, error conditions are modeled as subroutines returning either a result type or an error type. For example, in Scala:

```<code>def transferMoney(amount: Decimal): Either[String, Decimal]
</code>```

This is a stupid example, of course. The return type means "either return a string or a decimal". By convention, the left type is the error type (in this case, a string with the error message) and the right type is the result type.

This is similar to exceptions, except for the fact that exceptions also are control flow constructs. They are, in fact, equivalent in expressive power to GOTO.

Body:
Actually, it's not very uncommon at all to return different types even in a statically typed language. That's why we have union types, for example.

In fact, methods in Java almost always return one of four types: some kind of object or null or an exception or they never return at all.

In many languages, error conditions are modeled as subroutines returning either a result type or an error type. For example, in Scala:

def transferMoney(amount: Decimal): Either[String, Decimal]

This is a stupid example, of course. The return type means "either return a string or a decimal". By convention, the left type is the error type (in this case, a string with the error message) and the right type is the result type.

This is similar to exceptions, except for the fact that exceptions also are control flow constructs. They are, in fact, equivalent in expressive power to GOTO.


问:
Which is better: a bunch of getters or 1 method with a selection string parameter?
Our knowledge domain involves people walking over a pressure-recording plate with their bare feet. We do image recognition which results in objects of the 'Foot' class, if a human foot is recognized in the sensor data.

There are several calculations that must be performed on the foot's data.

Now, which API would be better:

```<code>class Foot : public RecognizedObject  {
  MaxPressureFrame getMaxPressureFrame();
  FootAxis getFootAxis();
  AnatomicalZones getAnatomicalZones();

  // + similar getters for other calculations

  // ...
}
</code>```

Or:

```<code>class Foot : public RecognizedObject {
  virtual CalculationBase getCalculation(QString aName);

  // ...
}
</code>```

Now, there are a lot of pro's and con's I can come up with, but I can't really decide which are the most important.
Note, this is an end-user application, not a software library we sell.

Any advice?

Some pro's for the first approach could be:

KISS - everything is very concrete. The API, but the implementation as well.

strongly typed return values.

inheriting from this class is fool-proof. Nothing can be overridden, only added.

API is very closed, nothing goes in, nothing can be overridden, so less can go wrong.

Some con's:

The number of getters will grow, as every new calculation we invent gets added to the list

API is more likely to change, and if breaking changes are introduced, we need a new API version, a Foot2.

in case of re-use of the class in other projects, we might not need every calculation

Some pro's for the second approach:

more flexible

the api is less likely to change, (assuming we got the abstraction correct, if not, changing will cost more)

Some con's:

loosely typed. Needs casts on every call.

the string parameter - I have bad feelings about that (branching on string values...)

There is no current use case/requirement that mandates the extra flexibility, but there might be in the future.

the API imposes restrictions: every calculation needs to derive from a base class. Getting a calculation will be forced through this 1 method, and passing extra parameters will be impossible, unless we devise an even more dynamic, super-flexible way of passing parameters which increases complexity even more.

答:
I would recommend option 3: Make it clear that the calculations are not an intrinsic part of the abstraction of a Foot, but operate on it. Then you can split Foot and the calculations into separate classes, like this:

```<code>class Foot : public RecognizedObject {
public:
    // Rather low-level API to access all characteristics that might be needed by a calculation
};

class MaxPressureFrame {
public:
    MaxPressureFrame(const Foot& aFoot); // Performs the calculation based on the information in aFoot
    //API for accessing the results of the calculation
};

// Similar classes for other calculations
</code>```

This way, you still have strong typing of your calculation, and you can add new ones without affecting existing code (unless you made a serious error in the amount information exposed by Foot).

Body:
I would recommend option 3: Make it clear that the calculations are not an intrinsic part of the abstraction of a Foot, but operate on it. Then you can split Foot and the calculations into separate classes, like this:

class Foot : public RecognizedObject {
public:
    // Rather low-level API to access all characteristics that might be needed by a calculation
};

class MaxPressureFrame {
public:
    MaxPressureFrame(const Foot& aFoot); // Performs the calculation based on the information in aFoot
    //API for accessing the results of the calculation
};

// Similar classes for other calculations

This way, you still have strong typing of your calculation, and you can add new ones without affecting existing code (unless you made a serious error in the amount information exposed by Foot).


答:
I think in first approach will pay off.
Magic strings can create the following issues:
Typing errors, misuse, non-trivial return type safety, lack of code completion, unclear code (did this version have that feature? i guess we'll find out at runtime). Using enums will resolve some of those issues, but let's look at the cons you raised:

The number of getters will grow, as every new calculation we invent gets added to the list

True, that can be annoying, however it keeps things nice and strict, and gives you code completion anywhere in your project in any modern IDE, with good heading comments that is much more useful than enums.

API is more likely to change, and if breaking changes are introduced, we need a new API version, a Foot2.

True, but that's actually a huge pro ;) you can define interfaces for partial APIs, and then you don't need to re-compile dependent class that are not affected by newer APIs (So no need for Foot2). That allows for better decoupling, the dependency is now of the interface and not the implementation.
Moreover if an existing interface changes, you will have a compilation error in dependent classes, which is great to prevent stale code.

in case of re-use of the class in other projects, we might not need every calculation

I don't see how using magic strings or enums will help with that... If I understand correctly, either you include the code in the Foot class or you break it down to a few smaller classes, and that goes for both options

Title: Which is better: a bunch of getters or 1 method with a selection string parameter?

Body:
Our knowledge domain involves people walking over a pressure-recording plate with their bare feet. We do image recognition which results in objects of the 'Foot' class, if a human foot is recognized in the sensor data.

There are several calculations that must be performed on the foot's data.

Now, which API would be better:

```<code>class Foot : public RecognizedObject  {
  MaxPressureFrame getMaxPressureFrame();
  FootAxis getFootAxis();
  AnatomicalZones getAnatomicalZones();

  // + similar getters for other calculations

  // ...
}
</code>```

Or:

```<code>class Foot : public RecognizedObject {
  virtual CalculationBase getCalculation(QString aName);

  // ...
}
</code>```

Now, there are a lot of pro's and con's I can come up with, but I can't really decide which are the most important.
Note, this is an end-user application, not a software library we sell.

Any advice?

Some pro's for the first approach could be:

KISS - everything is very concrete. The API, but the implementation as well.

strongly typed return values.

inheriting from this class is fool-proof. Nothing can be overridden, only added.

API is very closed, nothing goes in, nothing can be overridden, so less can go wrong.

Some con's:

The number of getters will grow, as every new calculation we invent gets added to the list

API is more likely to change, and if breaking changes are introduced, we need a new API version, a Foot2.

in case of re-use of the class in other projects, we might not need every calculation

Some pro's for the second approach:

more flexible

the api is less likely to change, (assuming we got the abstraction correct, if not, changing will cost more)

Some con's:

loosely typed. Needs casts on every call.

the string parameter - I have bad feelings about that (branching on string values...)

There is no current use case/requirement that mandates the extra flexibility, but there might be in the future.

the API imposes restrictions: every calculation needs to derive from a base class. Getting a calculation will be forced through this 1 method, and passing extra parameters will be impossible, unless we devise an even more dynamic, super-flexible way of passing parameters which increases complexity even more.


答:
I'm not sure, I'm getting your point here, but different kinds of languages don't really solve the underlying problem which is, basically, that a once written code base needs to be expanded. While this is something that refactoring, obviously, can solve, maybe the general concept/design of the code was unfortunate in the first place.

For instance, how about a Fighter (or a Person if you later change that) does "just something". Using, for example Java generics, you can even limit what they can do.

```<code>class Fighter {
    void doSomething(Command<? extends FighterCommand> cmd) {
        cmd.execute();
    }
}
</code>```

One can now easily, at any point during development, expand the abilities of a fighter by just adding another command.

```<code>class KickCommand extends FighterCommand {
    @Override
    public void execute() {
        kickSomeone();
    }
}
</code>```

Using the Command pattern here would absolve you from changing interfaces all over the place just because the fighter needs to punch someone now, too.

And getting closer to what you were asking, extending the Fighter concept to a Person concept should be possible by making the Fighter extend (the now new) Person. If a Person can doSomething(), too, it's only one @Override in the Fighter away (or deletion of the Fighter method :)).

Title: Is this how dynamic language copes with dynamic requirement?

Body:
The question is in the title. I want to have my thinking verified by experienced people. You can add more or disregard my opinion, but give me a reason.

Here is an example requirement: Suppose you are required to implement a fighting game. Initially, the game only includes fighters, who can attack each other. Each fighter can punch, kick or block incoming attacks. Fighters can have various fighting styles: Karate, Judo, Kung Fu... That's it for the simple universe of the game. In an OO like Java, it can be implemented similar to this way:

```<code>abstract class Fighter {
    int hp, attack;

    void punch(Fighter otherFighter);
    void kick(Fighter otherFighter);
    void block(Figther otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };
</code>```

This is fine if the game stays like this forever. But, somehow the game designers decide to change the theme of the game: instead of a simple fighting game, the game evolves to become a RPG, in which characters can not only fight but perform other activities, i.e. the character can be a priest, an accountant, a scientist etc... At this point, to make it more generic, we have to change the structure of our original design: Fighter is not used to refer to a person anymore; it refers to a profession. The specialized classes of Fighter (KaraterFighter, JudoFighter, KungFuFighter) . Now we have to create a generic class named Person. However, to adapt this change, I have to change the method signatures of the original operations:

```<code>class Person {
    int hp, attack;
    List<Profession> skillSet;
};

abstract class Profession {};

class Fighter extends Profession {
    void punch(Person otherFighter);
    void kick(Person otherFighter);
    void block(Person otherFighter);
};

class KarateFighter extends Fighter { //...implementation...};
class JudoFighter extends Fighter { //...implementation... };
class KungFuFighter extends Fighter { //...implementation ... };

class Accountant extends Profession {
     void calculateTax(Person p) { //...implementation...};
     void calculateTax(Company c) { //...implementation...};
};
//... more professions...
</code>```

Here are the problems:

To adapt to the method changes, I have to fix the places where the changed methods are called (refactoring).

Every time a new requirement is introduced, the current structural design has to be broken to adapt the changes. This leads to the first problem.

Rigid structure makes it hard for code reuse. A function can only accept the predefined types, but it cannot accept future unknown types. A written function is bound to its current universe and has no way to accommodate to the new types, without modifications or rewrite from scratch. I see Java has a lot of deprecated methods.

OO is an extreme case because it has inheritance to add up the complexity, but in general for statically typed language, types are very strict.

In contrast, a dynamic language can handle the above case as follow:

```<code>;;fighter1 punch fighter2
(defun perform-punch (fighter1 fighter2) ...implementation... )

;;fighter1 kick fighter2
(defun perform-kick (fighter1 fighter2) ...implementation... )

;;fighter1 blocks attacks from fighter2
(defun perform-block (fighter1 fighter2) ...implementation... )
</code>```

fighter1 and fighter2 can be anything as long as it has the required data for calculation; or methods (duck typing). You don't have to change from the type Fighter to Person. In the case of Lisp, because Lisp only has a single data structure: list, it's even easier to adapt to changes. However, other dynamic languages can have similar behaviors as well.

I work primarily with static languages (mainly C and Java, but working with Java was a long time ago). I started learning Lisp and some other dynamic languages this year. I can see how it helps improving my productivity.

Body:
I'm not sure, I'm getting your point here, but different kinds of languages don't really solve the underlying problem which is, basically, that a once written code base needs to be expanded. While this is something that refactoring, obviously, can solve, maybe the general concept/design of the code was unfortunate in the first place.

For instance, how about a Fighter (or a Person if you later change that) does "just something". Using, for example Java generics, you can even limit what they can do.

class Fighter {
    void doSomething(Command<? extends FighterCommand> cmd) {
        cmd.execute();
    }
}

One can now easily, at any point during development, expand the abilities of a fighter by just adding another command.

class KickCommand extends FighterCommand {
    @Override
    public void execute() {
        kickSomeone();
    }
}

Using the Command pattern here would absolve you from changing interfaces all over the place just because the fighter needs to punch someone now, too.

And getting closer to what you were asking, extending the Fighter concept to a Person concept should be possible by making the Fighter extend (the now new) Person. If a Person can doSomething(), too, it's only one @Override in the Fighter away (or deletion of the Fighter method :)).


问:
Python MVC framework for desktop applications
I'm used to program with Python and GTK using pygtk library.

I feel like my programs are not well separated according to MVC model.
I think following a framework it would help me to design better desktop
applications.

I'd like to know which Python MVC framework for desktop apps you're using and
why.

答:
first, I think Qt, and even it's Python bindings are way better structured than GTK; so you could first try it.

second, it seems you're slightly confused by the MVC buzzword.  It was originally defined as a modular architecture for GUI applications; unfortunately, there's a completely different layered architecture for Web apps also called MVC.

Maybe you feel your desktop apps are not very MVC because there not very web MVC, but they might be very GUI MVC nonetheless.


问:
Not copyrighting code and then reusing functions later
I'm coding something for my job to copy directories and then use regex to make all the filenames uniform.  I'm an undergrad student programmer for my university and I'm not sure what a professional coder would consider reasonable in this case. My job is mostly to implement mathematical research.  The current assignment is outside what I've been doing and seems like it would be really useful to have some of the functions available in case I (most likely) encounter a similar assignment at some point in my career in the future.  It's going to be really useful because the current filenames are so screwed right now that the admin assistants can't really keep up (and even trying to do so might just cause more human error).  I'm thinking that it may not overall be useful outside the current assignment because the regex will be so customised to the way the file are incorrectly named.

I'm wondering if this is simple work for a pro coder, and therefore I'm making this program to be much more important in my head than it actually is, or if this is something that a coder would really want to copyright or otherwise retain the ability to use this whenever and wherever else they feel like.  They've already told me that there is no question that I'll be given credit for the work, which I'm excited about.  My only concern was whether I should be thinking about reusing this code later or if this task is so generic that a pro coder would laugh about keeping the rights to such code.

This thread was interesting but seems different from my situation:

How can I reuse generic code for consulting between companies?

EDIT:

Florida, USA

答:
There are a couple ways you can handle this nicely:

a. Write the code, then get permission from your employer to publicly blog or otherwise make available the non confidential parts (exclude the regular expression for their particular file names for example).

Now, that code is in the public domain, you are free to copy and paste it later.

b. Create an exercise for yourself where you solve a similar problem. Write new code (don't copy what you wrote at work) to solve it. You now "own" your own solution to the problem which you can reuse anytime you wish.

In my case, I work on a lot of my own projects. While my company owns work I produce during work hours, if I create something similar for my personal use for something unrelated to work, they don't own it. At that point, if I happen to go work elsewhere, I'm certainly free to reuse my own independently written code.

*Note, I in no way suggest that you use anything designed specifically for your employer as your own! If confused - reread - it definitely says "create an exercise for yourself" which you work on on your own time. That's how you generate your own IP w/o having to get employer permission (caveat: don't run afoul of any non-competes).


答:
In dynamic-land it's all about duck-typing. The most responsible exposed/public-facing thing to do is to wrap potentially different types in a wrapper that gives them the same interface.

```<code>function ThingyWrapper(thingy){ //a function constructor (class-like thingy)

    //thingy is effectively private and persistent for ThingyWrapper instances

    if(typeof thingy === 'array'){
        this.alertItems = function(){
            thingy.forEach(function(el){ alert(el); });
        }
    }
    else {
        this.alertItems = function(){
            for(var x in thingy){ alert(thingy[x]); }
        }
    }
}

function gimmeThingy(){
    var
        coinToss = Math.round( Math.random() ),//gives me 0 or 1
        arrayThingy = [1,2,3],
        objectThingy = { item1:1, item2:2, item3:3 }
    ;

    //0 dynamically evaluates to false in JS
    return new ThingyWrapper( coinToss ? arrayThingy : objectThingy );
}

gimmeThingy().alertItems(); //should be same every time except order of numbers - maybe
</code>```

It might occasionally make sense to poop out different types altogether with no generic wrapper but honestly in 7ish years of writing JS, it's not something I've found it was reasonable or convenient to do very often. Mostly that's something I'd do in the context of closed environments like an object's interior where things are getting put together. But it's not something I've done often enough that any examples jump to mind.

Mostly, I would advise that you stop thinking about types as much altogether. You deal with types when you need to in a dynamic language. No more. It's the whole point. Don't check the type of every single argument. That's something I would only be tempted to do in an environment where the same method could give inconsistent results in unobvious ways (so definitely don't do something like that). But it's not the type that matters, it's how whatever it is that you give me works.

Title: Is it a bad idea to return different data types from a single function in a dynamically typed language?

Body:
My primary language is statically typed (Java).  In Java, you have to return a single type from every method.  For example, you can't have a method that conditionally returns a String or conditionally returns an Integer.  But in JavaScript, for example, this is very possible.

In a statically typed language I get why this is a bad idea.  If every method returned Object (the common parent all classes inherit from) then you and the compiler have no idea what you're dealing with.  You'll have to discover all your mistakes at run time.

But in a dynamically typed language, there may not even be a compiler.  In a dynamically typed language, it's not obvious to me why a function that returns multiple types is a bad idea.  My background in static languages makes me avoid writing such functions, but I fear I'm being close minded about a feature that could make my code cleaner in ways I can't see.

Edit: I'm going to remove my example (until I can think of a better one).  I think it's steering people to reply to a point I am not trying to make.

Body:
In dynamic-land it's all about duck-typing. The most responsible exposed/public-facing thing to do is to wrap potentially different types in a wrapper that gives them the same interface.

function ThingyWrapper(thingy){ //a function constructor (class-like thingy)

    //thingy is effectively private and persistent for ThingyWrapper instances

    if(typeof thingy === 'array'){
        this.alertItems = function(){
            thingy.forEach(function(el){ alert(el); });
        }
    }
    else {
        this.alertItems = function(){
            for(var x in thingy){ alert(thingy[x]); }
        }
    }
}

function gimmeThingy(){
    var
        coinToss = Math.round( Math.random() ),//gives me 0 or 1
        arrayThingy = [1,2,3],
        objectThingy = { item1:1, item2:2, item3:3 }
    ;

    //0 dynamically evaluates to false in JS
    return new ThingyWrapper( coinToss ? arrayThingy : objectThingy );
}

gimmeThingy().alertItems(); //should be same every time except order of numbers - maybe

It might occasionally make sense to poop out different types altogether with no generic wrapper but honestly in 7ish years of writing JS, it's not something I've found it was reasonable or convenient to do very often. Mostly that's something I'd do in the context of closed environments like an object's interior where things are getting put together. But it's not something I've done often enough that any examples jump to mind.

Mostly, I would advise that you stop thinking about types as much altogether. You deal with types when you need to in a dynamic language. No more. It's the whole point. Don't check the type of every single argument. That's something I would only be tempted to do in an environment where the same method could give inconsistent results in unobvious ways (so definitely don't do something like that). But it's not the type that matters, it's how whatever it is that you give me works.


答:
No answer has yet mentioned SOLID principles.  In particular, you should follow the Liskov substitution principle, that any class receiving a type other than the expected type can still work with whatever they get, without doing anything to test what type is returned.

So, if you throw some extra properties onto an object, or wrap a returned function with some kind of decorator that still accomplishes what the original function was intended to accomplish, you are good, as long as no code calling your function ever relies on this behavior, in any code path.

Instead of returning a string or an integer, a better example might be it returns a sprinkler system or a cat.  This is fine if all the calling code is going to do is call functionInQuestion.hiss().  Effectively you have an implicit interface that the calling code is expecting, and a dynamically typed language won't force you to make the interface explicit.

Sadly, your co-workers probably will, so you probably have to do the same work anyway in your documentation, except there isn't a universally accepted, terse, machine-analyzable way to do it - as there is when you define an interface in a language that has them.


问:
Is mentioning my blog on my resume helpful or hurtful to a job search?
I have a blog that I use mostly to record solutions to problems I have had, that I had some trouble finding an answer to. Mostly problems where the online doc I googled provided too much info, and I found the answer to my question on the fifth page of my third google hit.

(Or if I asked the question here, I either didn't get an answer or I got slammed for asking a question that "the answer could be easily googled.")

I frequently look up stuff on this blog to remind myself of how I solved a problem, and it gets a decent amount of hits from others as well.

Anyway, I was wondering if mentioning this blog on my resume would help or hurt me in a job search? The topics are all over the map.

What I would hope it shows is that

I am a person who finds solutions to problems

I have used many different technologies in my work

I am not afraid to tackle a challenge

What I am concerned it shows is that

This person had trouble with something that simple?

Why is this person bothering to blog this stuff?

答:
Demonstrating you can code is a major part of the interview process. Many have indicated that college degrees, certifications, and resume exaggerations are no help in differentiating job candidates. Seems like S.O., a technical blog, presenting at a conference, a website you built, code on github/open source project would be excellent ways to create a portfolio of your work and skill set. Strong references are important as well.

I thought we were moving away from the hiring strategies of the 1950's? Apparently not.


答:
A dynamic language may complain less when you refactor, but it could also be hiding type errors from you that you'd catch at compile time on a statically typed language. In general, you'll have to refactor your code when your requirements change regardless of whether you're on a dynamic or statically typed language. There's no silver bullet there.

C and Java aren't good benchmarks for static languages, because they have very limited type systems and features. You can't get anything done in Java without extreme verbosity. Want to pass a tuple? Well, you can't. Records? You can't. Want an anonymous function? You'll have to write 4 lines of boilerplate for a payload that could be as short as 2 + 2. God help you if you want to curry or compose functions.

You have to resort to a bunch of OO hacks to work around those missing features, and even then you can still shoot yourself in the foot with inheritance and null because so many people don't understand how dangerous they are. So if that's your only point of reference, just about any dynamic language will allow you to write less code, but not necessarily by virtue of their dynamic typing. Languages like Standard ML or F# also provide those features without burdening you with type annotations because the compiler can infer the types.

A good statically-typed language is more expressive than a dynamically typed language with equivalent features. Dynamic typing deprives you of the ability to express constraints on your data using the type system. That's because dynamic typing is a special case of static typing - it's more correct to think of these languages as being unityped. If that seems strange to you, imagine coding in Java using only Object variables and casts. The problem is that mainstream statically typed languages are crippled. But if you're coding in Lisp, I don't think you're too concerned with what's mainstream.


问:
Can we say that Java or C# have unified inheritance trees?
Can we say that Java or C# are OO languages with a unified inheritance tree/unified type system?
By unified inheritance tree/unified type system I mean that every class derives implicitly or explicitly from one single type? Are there any object oriented language that do not follow that concept?</p>

答:
You could argue that the two languages are strictly hierarchical since they both require inheritance from a base Object class.  But I'm not sure what that claim would buy you.  They're object oriented languages and they use a base Object to facilitate some language features.  Worrying about "strictly hierarchical" doesn't help a conversation about OO languages.

Are there any objective language that do not follow that concept?

To my knowledge, C++ doesn't rely upon a unified inheritance tree.  For that matter, languages which aren't strictly or statically typed have no need for a unified inheritance tree, this group includes SmallTalk, Perl, JavaScript, and many others.

Then there's prototypal inheritance which is unarguably OO, but attempts to accomplish the general goals of OO in a way which makes a unified type system irrelevant, because prototypal inheritance is used for extending things rather than distinguishing them.

At the end of the day it's worth noting that type systems and language design are two interwoven topics which are very complex where solutions are extremely diverse. Given the diversity and number of languages out there, you can likely find languages that approach these varying problems in as many ways as can be imagined.

To further compound the situation, it's also worth noting that the definition of "object oriented" or "objective" is not only wishy-washy but extremely controversial as you can find in many places across the internet, for example here you can find the inventor of the term advocating it's meaning as something far different from prototypal OO or C#/Java's OO, and to this day people don't agree on it's definition.

Here are some links to support Java & C#'s use of a base Object class.

Oracle's Java documentation

Excepting Object, which has no superclass, every class has one and only one direct superclass (single inheritance). In the absence of any other explicit superclass, every class is implicitly a subclass of Object.

MS documentation on C#

Supports all classes in the .NET Framework class hierarchy and provides low-level services to derived classes. This is the ultimate base class of all classes in the .NET Framework; it is the root of the type hierarchy.

Related SO question about inheriting from system.object

This answer on SO explains why C++ doesn't have a universal base object.


问:
Why most "well-known" imperative/OO languages allow unchecked access to types that can represent a 'nothing' value?
I have been reading about the (un)convenience of having null instead of (for example) Maybe. After reading this article, I am convinced that it would be much better to use Maybe (or something similar). However, I am surprised to see that all the "well-known" imperative or object oriented programming languages still use null (which allows unchecked access to types that can represent a 'nothing' value), and that Maybe is mostly used in functional programming languages.

As an example, look at the following C# code:

```<code>void doSomething(string username)
{
    // Check that username is not null
    // Do something
}
</code>```

Something smells bad here... Why should we be checking if the argument is null? Shouldn't we assume that every variable contains a reference to an object? As you can see, the problem is that by definition almost all variables can contain a null reference. What if we could decide which variables are "nullable" and which not? That would save us a lot of effort while debugging and looking for a "NullReferenceException". Imagine that, by default, no types could contain a null reference. Instead of that, you would state explicitly that a variable can contain a null reference, only if you really need it. That is the idea behind Maybe. If you have a function that in some cases fails (for example division by zero), you could return a Maybe<int>, stating explicitly that the result may be an int, but also nothing! This is one reason to prefer Maybe instead of null. If you are interested in more examples, then I suggest to read this article.

The facts are that, despite the disadvantages of making most types nullable by default, most of the OO programming languages actually do it. That is why I wonder about:

What kind of arguments would you have to implement null in your programming language instead of Maybe? Are there reasons at all or is it just "historical baggage"?

Please ensure you understand the difference between null and Maybe before answering this question.

答:
I think the fundamental reason is that relatively few null checks are required to make a program "safe" against data corruption.  If a program tries to use the contents of an array element or other storage location which is supposed to have been written with a valid reference but wasn't, the best-case outcome is for an exception to be thrown.  Ideally, the exception will indicate exactly where the problem occurred, but what matters is that some kind of exception gets thrown before the null reference gets stored somewhere that could cause data corruption.  Unless a method stores an object without trying to use it in some fashion first, an attempt to use an object will--in and of itself--constitute a "null check" of sorts.

If one wants to ensure that an null reference which appears where it shouldn't will cause a particular exception other than NullReferenceException, it will often be necessary to include null checks all over the place.  On the other hand, merely ensuring that some exception will occur before a null reference can cause "damage" beyond any that has already been done will often require relatively few tests--testing would generally only be required in cases where an object would store a reference without trying to use it, and either the null reference would overwrite a valid one, or it would cause other code to misinterpret other aspects of program state.  Such situations exist, but aren't all that common; most accidental null references will get caught very quickly whether one checks for them or not.


问:
Does a team of developers need a manager?
Background:

I'm currently part of a team of four: 1 manager, 1 senior developer and 2 developers. We do a range of bespoke in-house systems / projects (e.g. 6-8 weeks) for an organisation of around 3500 staff, as well as all the maintenance and support required from the systems that have been created before. There is not enough of us to do all the work that is potentially coming our way - we're understaffed. Management acknowledge this, but budget restraints limit our ability to recruit additional members to the team (even if we make the salary back in savings).

The Change

This leaves us where we are now. Our manager is due to leave his role for pastures new, leaving a vacancy in the team. Management are using this opportunity to restructure our team which would see the team manager role replaced by another developer and another senior developer. Their logic being that we need more developers, so here's a way of funding it (one of the roles is partially funded from another vacant post).

The team would have no direct line manager and the roles and responsibilities would be divided up between the seniors and the (relatively new to post) service manager (a non-technical role with little-to-no development knowledge/experience whose focus is shared amongst a number of other teams and individuals) - who would be our next actual manager up the food chain.

I guess the final question is:

Is it possible to run a development team without an manager? Have you had experience of this? And what things could go wrong / could be of benefit to us?

I'd ideally like to "see the light" and the benefits of doing things this way, or come up with some points for argument against it.

答:
I work for a company where we embrace agile practices, in particular Scrum. It works great across the board: development teams, and executive management are all happy. They get what they want.

All engineers report to Engineering Manager. Engineering Manager is an extremely technical and functional role, with the role requiring to get more business to the division. This role is equivalent to Product Owner.

The project manager is a separate role, akin a scrum master, and is usually a contractor for a fixed time (12 months to 18 months, with no extensions to contract)

The project manager--scrum master--is completely responsible for non-functional and non-engineering activities

This has worked wonderfully, as the development team focuses on the engineering aspects, business analysts/product owners focus on the business aspects. The project manager is responsible for task tracking, reporting and other typical Scrum Master duties.

The middle management is outsourced, and there is no growth path from middle management to top management. The growth opportunity is from development team or business analysts role to  engineering manager, and not from supervisory roles.

Our company strongly believes that middle management is not a major value add to a company, and is best left to external consulting companies.


问:
Can removing unnecessary file from a repo be considered part of refactoring?
We're using Git as our DVCS and we're about to start to do a clean up (never done before in this team) of files that are not necessary (not part of the sources) from our products.

This is done in two ways:

removing the product files from the repo and adding them to the ignore list.

deleting dead code

According to Wikipedia:

Code refactoring is the process of restructuring existing computer code without changing its external behavior. Refactoring improves nonfunctional attributes of the software. Advantages include improved code readability and reduced complexity to improve source code maintainability, and create a more expressive internal architecture or object model to improve extensibility.

and from Martin Fowler's entry:

Refactoring is a very specific technique, founded on using small behavior-preserving transformations (themselves called refactorings).

I haven't read anywhere that removing dead code or removing files from your repo are considered refactoring techniques but I see them both as techniques that "improve source code maintainability" by removing irrelevant code that may distract us later on.

Do you think it's reasonable to call those two activities "Refactoring"?

答:
I had to stop and think for a minute. This is not refactoring all on its own, but it's completing someone's refactoring or feature which was never finished.

Think about how the inert resources and dead code works its way into the codebase.

It was added, but never used. Someone began a refactoring or started a feature but never completed that task.

It was a tagalong with other useful code. Someone needed 1 function, but they added a whole directory of code/resources just to get that 1 function.

New logic caused the resources/code to be abandoned. A re-skin was done, but the old resources were never removed. A refactoring caused unused classes/functions, but that code was never removed.

In all of these cases, if the work was properly completed, the cleanup would have been done as a part of that task.

Now you need to go back and finish those old tasks. It's not refactoring. It's completing old work.


问:
What are and how do (data-) types work?

What is a "variable"/data type?

How does a compiler / interpreter handle types?

My specific concern has to do with the different types in lower and higher level languages. For instance in Python, as list is really flexible. You can just define it and put in at runtime whatever you want.

ints

floats

strings

sets

even other lists

Basically objects of any type (if I'm not mistaken).

So I imagine list to be a class written in C with really a lot of stuff in there, dynamic memory allocation and so on and so forth, to handle all this.

Is that right?

..and does that mean all those e. g. Python types are C classes?

Then what are types in C?

Are they "classes"?

..or somehow related to assembler code?

PS: I'm not looking for some precise illustrative hints and answers rather than for a wide exhaustive explanation. And: This questions are not related to "There are no variables in Python, but identifiers".

答:
You're basically right. Python types are just wrappers around C types (technically, there are no classes in C). These wrappers implement very specifically defined behaviors for Python. In the case of lists, the Python FAQ shows that they are implemented in C as an array of pointers, and resized when necessary (such as inserting or deleted objects), with a bit of added optimization.

This is the kind of thing that programmers working in C have had to do for themselves for a long time. Python just takes care of all of this for you in the background so you don't have to worry about it.

As far as Python types being C classes, or What are C types?, you can consider C types to be the building blocks that Python is built on. In the same way that a hash table is built on lists, but with added functionality to provide a specific service (fast insert/lookup), Python types/classes are built on C types, with added functionality.

Title: What are and how do (data-) types work?


问:
should this code be structured into an event capture and a method or put the functionality in the event capturing
I have adopted some jQuery code that has like 20 event-captures that look like this

```<code>  // used on menu#edit
  $('.show-headers-only-toggle').on('click',function(){
    arc_eh.menu_edit.show_headers_only_toggle.call(this);
  });
</code>```

that call a method that does the functionality. This is the only place that this method is called. I want to put the functionality after the event like this since I think there's no reason to have this other method. The argument for having it in a method is that I'm polluting this space and the event handling is like a router and this is a controller. I feel like this is bikeshedding and we're not using a framework so it's just simpler to have all in place. Who do you feel is wrong in this? I feel they are bikeshedding this.

```<code>  // used on menu#edit
  $('.show-headers-only-toggle').on('click',function(){
    var action=$(this).attr('arc-action');
    // this would just be what is in the function above
    if(action=='hide-items'){
      $('.menu-item-admin').hide();
      $(this).text('show items');
      $(this).attr('arc-action','show-items');
    }else{
      $(this).text('show headers only');
      $('.menu-item-admin').show();
      $(this).attr('arc-action','hide-items');
    }
  });
</code>```

答:
I greatly prefer the first chunk of code.  The fact that it is only used once doesn't matter.  The great thing about small methods is that you can show intentions of the code without having to read it.  You might want to check out something like Clean Code, the early chapters really talk about the importance of well named methods.

```<code>$('.show-headers-only-toggle').on('click',function(){
    arc_eh.menu_edit.show_headers_only_toggle.call(this);
  })
</code>```

Without knowing anything of your code base I can assume that the following method toggles the headers of an edit menu.  Looking at the other chunk of code I really can't tell what it is doing without reading the code.

There are also other benefits too.  What happens when you want to have that functionality outside of just a mouse click for example in a hot key?  Also how are you going to test that the method works?  There are frameworks that can fire events on dom elements but that can add extra bloat and event knowledge to your tests.

Body:
I greatly prefer the first chunk of code.  The fact that it is only used once doesn't matter.  The great thing about small methods is that you can show intentions of the code without having to read it.  You might want to check out something like Clean Code, the early chapters really talk about the importance of well named methods.

$('.show-headers-only-toggle').on('click',function(){
    arc_eh.menu_edit.show_headers_only_toggle.call(this);
  })

Without knowing anything of your code base I can assume that the following method toggles the headers of an edit menu.  Looking at the other chunk of code I really can't tell what it is doing without reading the code.

There are also other benefits too.  What happens when you want to have that functionality outside of just a mouse click for example in a hot key?  Also how are you going to test that the method works?  There are frameworks that can fire events on dom elements but that can add extra bloat and event knowledge to your tests.


问:
Low level programming - what's in it for me?
For years I have considered digging into what I consider "low level" languages. For me this means C and assembly. However I had no time for this yet, nor has it EVER been neccessary.

Now because I don't see any neccessity arising, I feel like I should either just schedule some point in time when I will study the subject or drop the plan forever.

My Position

For the past 4 years I have focused on "web technologies", which may change, and I am an application developer, which is unlikely to change.

In application development, I think usability is the most important thing. You write applications to be "consumed" by users. The more usable those applications are, the more value you have produced.

In order to achieve good usability, I believe the following things are viable

Good design: Well-thought-out features accessible through a well-thought-out user interface.

Correctness: The best design isn't worth anything, if not implemented correctly.

Flexibility: An application A should constantly evolve, so that its users need not switch to a different application B, that has new features, that A could implement. Applications addressing the same problem should not differ in features but in philosophy.

Performance: Performance contributes to a good user experience. An application is ideally always responsive and performs its tasks reasonably fast (based on their frequency). The value of performance optimization beyond the point where it is noticeable by the user is questionable.

I think low level programming is not going to help me with that, except for performance. But writing a whole app in a low level language for the sake of performance is premature optimization to me.

My Question

What could low level programming teach me, what other languages wouldn't teach me? Am I missing something, or is it just a skill, that is of very little use for application development? Please understand, that I am not questioning the value of C and assembly. It's just that in my everyday life, I am quite happy that all the intricacies of that world are abstracted away and managed for me (mostly by layers written in C/C++ and assembly themselves). I just don't see any concepts, that could be new to me, only details I would have to stuff my head with. So what's in it for me?

My Conclusion

Thanks to everyone for their answers. I must say, nobody really surprised me, but at least now I am quite sure I will drop this area of interest until any need for it arises.

To my understanding, writing assembly these days for processors as they are in use in today's CPUs is not only unneccesarily complicated, but risks to result in poorer runtime performance than a C counterpart. Optimizing by hand is nearly impossible due to OOE, while you do not get all kinds of optimizations a compiler can do automatically. Also, the code is either portable, because it uses a small subset of available commands, or it is optimized, but then it probably works on one architecture only.

Writing C is not nearly as neccessary anymore, as it was in the past. If I were to write an application in C, I would just as much use tested and established libraries and frameworks, that would spare me implementing string copy routines, sorting algorithms and other kind of stuff serving as exercise at university. My own code would execute faster at the cost of type safety. I am neither keen on reeinventing the wheel in the course of normal app development, nor trying to debug by looking at core dumps :D

I am currently experimenting with languages and interpreters, so if there is anything I would like to publish, I suppose I'd port a working concept to C, although C++ might just as well do the trick.

Again, thanks to everyone for your answers and your insight.

答:
I think nowadays low and high level programming can be quite separated. Basically this means that you could live all your professional life without knowing C and assembler with no problems at all.
That said the C programming language cannot teach you a lot from programming and design  points of view.

Just out of curiosity you could learn how things works in a lower level. When I was at University, for example, I enjoyed using gcc to generate assembler code from C++. It was useful to comprehend how polymorfism and exception are implemented. But apart from that the only things you could learn from C nowadays are:

1) dirty memory tricks. C is the best way to understand that there is no bottom down in programmers madness :)

2) GOTOs are actually used (and useful) to rollback errors

3) learn better how memory allocation works (difference between heap and stack anyone?).

So basically my thesis is: if you already finished University and you still don't need C, than don't learn it :)


问:
What changes can I make to my IDE to minimize the effect of my dyslexia?
I program and I am dyslexic. My vision is excellent. I do poorly processing symbols and am a visual thinker.

When I code, I'm slower than normal people because I am unpredictably unaware of the errors I make. I am learning python and the text only development environments cause me a lot of visual stress; I am using Wingware which is somewhat helpful, but cant complete assignments in the time given.

Can you suggest an accommodation that would help me?

What adaptations would be helpful to me?

Is there any way I can automatically find, highlight and fix these kinds of errors?

Proofreading, I see what I expect to see or something familiar. I don't notice typos, skip lines etc and the bugs turn up in testing. Even copy & pasting I can miss lines and cause errors.

Blocks of text from margin to margin give me headaches as do some color combinations

I do not process text as symbols, rather as objects that can be rotated, transposed so that the digits in a number move to different places, I may perceive "123" AS "132", THE LETTERS "pddq", look the same to me. I think of these as tricky - the same shape rotated and reflected.

答:
Some things that help are:

Use light text on a dark background.  A soft font colour other than white can really help as well (green on black is really good, and retro too!)

Autocomplete is a huge boon.  You should just be typing the first couple of letters of a variable and then pressing your autocomplete button.

Static languages tend to work better for code completion and compilation checks than dynamic languages.

If you do use a dynamic language, use Test Driven Development.  Find your errors as soon as possible.

Don't use cryptic names for variables and functions (which is sadly all too popular).


问:
is it a bad programming practice to return a new object in a property
I've always had this question and I think it is time to settle the answer, is it a heavy load to do this :

```<code>    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            return new Rect(callOutStarMargin, Top, _size, _size);
        }
    }
</code>```

as an alternative of this :

```<code>    private Rect _boundsRect = new Rect();

    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            _boundsRect.Y = Top;
            return _boundsRect;
        }
    }
</code>```

doing this I'm avoiding to create a new Rect everytime the property is invoked, I'm not sure if doing this in the first way would create an extra memory/speed overweight, if lets say this property is accessed 1 or 2 times on a list of 100 items each second.

So which one should I choose ?

EDIT:

I think I'm not being clear here, my real question is How heavy is it making this new instructions of simple objects like Rect, How efficient is C# garbage collector for example in this scenario of 100 new rects per second , and the cpu cycle difference between one or the other way

答:
It's not uncommon, or bad, to return new objects from properties (as immutable types do this all the time).

Ultimately, it's not an issue until you've measured it and found it to be an issue.


问:
Large number of projects for a single application
I'm working on 300K line C/C++ Windows application that is spread across 23 different Eclipse projects (approximately one third for Qt interface, one third for DLLs and one third for static libraries).

I have complained to the project manager that it's cumbersome to work with so many different projects for one single piece of software. For example, if I change one thing at a static library, I will probably have to recompile at least 5 other projects.

Am I right to complain or is this how most similar projects are managed? Is there any reference on how it should be done?

答:
If the product I worked on was all in one (or even some small set) of projects, it would take days (literally) to compile the whole thing.

A proper source tree that explicitly states its dependencies is critically important to enable things like partial/incremental builds, but the number of projects is not a metric that you should need to concentrate on optimizing for.

In your case, you likely work on some shared resource/library, which is what is requiring recompilation of all the projects that have taken a dependency on it. To an extent you can minimize recompilation with SOA and having hard restrictions on the changes people are allowed to make to the contract/interface of the service.


答:
There are three things you need to consider when deciding if a property should send a new object or a reference to a maintained object, and each of these will vary by language and runtime.

What will avoid inappropriate errors.  If you pass a reference to a private object, it's theoretically possible that downstream consumers of your class may hit an error when your object is deleted or updated and they still have a reference.  (If this isn't an issue on your platform, don't worry about it.)

What will avoid unacceptable performance.  As with the above, you may get a performance hit by creating new objects on each reference instead of passing the same object around.  This can vary very substantially even within the same language: early Java implementations had expensive object-creation, while modern Java creates and destroys objects with far better performance.

What will those who come after you expect.  If neither of the above are an issue, you should follow whatever is traditionally done in your project.  It'd be aggravating to expect a stored reference to your object's Top object to update when it doesn't, or vice-versa.

Personally, I grew up on JavaScript, and so prefer object references that persist themselves, and primitives that don't.  But that's just me, and the languages I do most of my work in now have considerably different behavior.

Title: is it a bad programming practice to return a new object in a property

Body:
I've always had this question and I think it is time to settle the answer, is it a heavy load to do this :

```<code>    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            return new Rect(callOutStarMargin, Top, _size, _size);
        }
    }
</code>```

as an alternative of this :

```<code>    private Rect _boundsRect = new Rect();

    public Rect Bounds
    {
        get
        {
            var Top = (_targetPosition + _translationY) - _size / 2.0f;
            _boundsRect.Y = Top;
            return _boundsRect;
        }
    }
</code>```

doing this I'm avoiding to create a new Rect everytime the property is invoked, I'm not sure if doing this in the first way would create an extra memory/speed overweight, if lets say this property is accessed 1 or 2 times on a list of 100 items each second.

So which one should I choose ?

EDIT:

I think I'm not being clear here, my real question is How heavy is it making this new instructions of simple objects like Rect, How efficient is C# garbage collector for example in this scenario of 100 new rects per second , and the cpu cycle difference between one or the other way


问:
Inheritance vs mixins in dynamic languages?
When should you prefer inheritance patterns over mixins in dynamic languages?

By mixins, I mean actual proper mixing in, as in inserting functions and data members into an object in runtime.

When would you use, for example, prototypal inheritance instead of mixins? To illustrate more clearly what I mean by mixin, some pseudocode:

```<code>asCircle(obj) {
  obj.radius = 0
  obj.area = function() {
    return this.radius * this.radius * 3.14
  }

myObject = {}
asCircle(myObject)
myObject.area() // -> 0
</code>```

答:
Well, the best example I can give it to you is an Actor for a game which has inheritance for some base stuff but uses mixins/plugins for shared functionality. The shared functionality could be (directly from the source code!):</p>

```<code>var plugins = {
    SingleVisualEntity : SingleVisualEntity,
    JumpBehaviour      : JumpBehaviour,
    WeaponBehaviour    : WeaponBehaviour,
    RadarBehaviour     : RadarBehaviour,
    EnergyGatherer     : EnergyGatherer,
    LifeBarPlugin      : LifeBarPlugin,
    SelectionPlugin    : SelectionPlugin,
    UpgradePlugin      : UpgradePlugin,
    BrainPlugin        : BrainPlugin,
    PlanetObjectPlugin : PlanetObjectPlugin,
}
</code>```

Body:
Well, the best example I can give it to you is an Actor for a game which has inheritance for some base stuff but uses mixins/plugins for shared functionality. The shared functionality could be (directly from the source code!):

var plugins = {
    SingleVisualEntity : SingleVisualEntity,
    JumpBehaviour      : JumpBehaviour,
    WeaponBehaviour    : WeaponBehaviour,
    RadarBehaviour     : RadarBehaviour,
    EnergyGatherer     : EnergyGatherer,
    LifeBarPlugin      : LifeBarPlugin,
    SelectionPlugin    : SelectionPlugin,
    UpgradePlugin      : UpgradePlugin,
    BrainPlugin        : BrainPlugin,
    PlanetObjectPlugin : PlanetObjectPlugin,
}


问:
Mental schema for SQL queries
While preparing SQL introductory material, I've ended asking myself about the line of thought followed by a developer when writing a query. I believe it could be too valuable from a beginner's point of view.

Let me illustrate the subject with an example. For the sake of brevity, I won't include the database schema, hoping for the query to be descriptive enough by itself.

Suppose we want to write a query for retrieving all new customers from the last quarter. Typical. Me, the first thing I think about is the set of entities involved, beginning with the ones corresponding to the requested data. So, as I want to get customers, first of all I write the following query skeleton:

```<code>    SELECT
      FROM Customers AS NewCustomer
     WHERE
</code>```

There immediately follow the remaining entities. In this fictional context, a new customer is any customer having placed an order for the first time:

```<code>    SELECT
      FROM Customers AS NewCustomer
INNER JOIN Orders AS RecentOrder
 LEFT JOIN Orders AS OlderOrder
     WHERE
       AND OlderOrder.Id IS NULL
</code>```

With all the entities identified, I proceed writing the relations between them:

```<code>    SELECT
      FROM Customers AS NewCustomer
INNER JOIN Orders AS RecentOrder
        ON RecentOrder.CustomerId = NewCustomer.Id
 LEFT JOIN Orders AS OlderOrder
        ON OlderOrder.CustomerId = RecentOrder.CustomerId
       AND OlderOrder.PlacementDate < RecentOrder.PlacementDate
     WHERE
       AND OlderOrder.Id IS NULL
</code>```

Once I'm finished with the entities, it's time for me to define whatever restrictions to be applied over the resulting data set:

```<code>    SELECT
      FROM Customers AS NewCustomer
INNER JOIN Orders AS RecentOrder
        ON RecentOrder.CustomerId = NewCustomer.Id
 LEFT JOIN Orders AS OlderOrder
        ON OlderOrder.CustomerId = RecentOrder.CustomerId
       AND OlderOrder.PlacementDate < RecentOrder.PlacementDate
     WHERE RecentOrder.PlacementDate BETWEEN @fromDate AND @toDate
       AND OlderOrder.PlacementDate < @fromDate
       AND OlderOrder.Id IS NULL
</code>```

Finally, I ask myself which concrete data fields I want the query to return, thus completing the SELECT clause:

```<code>    SELECT NewCustomer.FirstName, NewCustomer.LastName
      FROM Customers AS NewCustomer
INNER JOIN Orders AS RecentOrder
        ON RecentOrder.CustomerId = NewCustomer.Id
 LEFT JOIN Orders AS OlderOrder
        ON OlderOrder.CustomerId = RecentOrder.CustomerId
       AND OlderOrder.PlacementDate < RecentOrder.PlacementDate
     WHERE RecentOrder.PlacementDate BETWEEN @fromDate AND @toDate
       AND OlderOrder.PlacementDate < @fromDate
       AND OlderOrder.Id IS NULL
</code>```

Of course, this is a very simple query, without aggregates, nested queries and other advanced stuff. But this is my overall train of thought, whatever the query's complexity:

Entities

Relations

Restrictions

Fields

My question is, is this a suitable schema to be taught explicitly to a beginner? How could it be improved, anyway, in order to smooth her learning curve?

答:
tl;dr

I think you have it exactly backwards.

A knowledgeable developer constructs his queries in the order you mention there because that is the order of dependencies - You don't know what relations you need to follow until you know what entities you need, you don't know what restrictions are necessary without first identifying your relations, and you can't know what to restrict on until you know the field set at your disposal.

Therefore a knowledgeable developer often times follows the order as set forth because in the real world we need the highest level component - the entity - and that part drives how we use all the others.

However, this order is from highest level most dependant to lowest level least dependant pieces. For someone who's unfamiliar with SQL you don't want to teach entities first when they don't yet know about relations, restrictions, or fields; transitively you shouldn't teach relations to someone who doesn't know restrictions or fields, or restrictions to someone who doesn't know fields.

Given the concept you're detailing above and the break down the way I see it, you should teach them in precisely the opposite order as you have suggested.

I think this becomes obvious if you look at the example query you have above - to query for conceptual entities you end up with a query far more complex than a new SQL developer should have to look at first. Further, until the last piece you haven't got a completed SQL query because your last thing to teach is the most dependent piece that every other piece requires just to work at all. The way you suggest going about it would have you giving incomplete SQL examples as you have above until you were done teaching all of the concepts, it seems more reasonable to give smaller complete examples that grow more complex rather than growing more complete.

Title: Mental schema for SQL queries


答:
What you may want to keep in mind is that callers may assume that the value of a property does not change unless it has been explicitly assigned. This isn't necessarily a smart assumption, but nevertheless it is one that will be made.

Many programmers would expect the following test to pass:

```<code>var b1 = foo.Bounds;
var b2 = foo.Bounds;
Assert.AreEqual(b2, b1);
</code>```

Now, for something like a Rect, this probably isn't a major problem, especially if it's immutable (as a Rect normally would be) and either a value type or has a value-equality operator. In this case, it really doesn't matter if two different calls get two different instances because it's very difficult to write code that implicitly depends on them being the same instance.

Also, lazy instantiation is almost always fine:

```<code>public Rect Bounds
{
    get
    {
        if (bounds == null)
            bounds = GetBounds(...);
        return bounds;
    }
}
</code>```

...because subsequent calls will get the same instance, barring any multi-threading problems.

But things can get hairy when a property actually returns a different instance every time, and that instance is a fairly complex and especially mutable object.

For example, let's say you return a Stream:

```<code>public Stream OutputStream
{
    get { return new FileStream(...); }
}
</code>```

This is fairly horrible because someone's very likely to write code like:

```<code>foo.OutputStream.Write(data1, 0, data1.Length);
foo.OutputStream.Write(data2, 0, data2.Length);
</code>```

And depending on exactly how you've implemented OutputStream, one of two nasty things will happen, either there will be a file-locking exception on the second call, if OutputStream always references the same file, or the caller might unintentionally write data to two different files (if, let's say, OutputStream actually creates a new file each time), subsequently corrupting both files.

Don't expect callers to save the return value of a property. They often won't. So if you're considering writing a property that returns a different object each time, make sure that there aren't any serious risks to having two instances floating around at the same time and possibly being swapped or lost.

I've spent many a painful hour debugging code where it looked like everything was working correctly but it turned out I was only working on a copy of the correct instance. Iterators with deferred execution are an especially pernicious subset of this problem; it's not uncommon to foreach through it once and change some property of each element, then foreach through it again and find that everything has "reset"!

One last thing - you should never new up an object that requires cleanup from a property accessor. There's almost no chance at all that the caller will clean it up.

Body:
What you may want to keep in mind is that callers may assume that the value of a property does not change unless it has been explicitly assigned. This isn't necessarily a smart assumption, but nevertheless it is one that will be made.

Many programmers would expect the following test to pass:

var b1 = foo.Bounds;
var b2 = foo.Bounds;
Assert.AreEqual(b2, b1);

Now, for something like a Rect, this probably isn't a major problem, especially if it's immutable (as a Rect normally would be) and either a value type or has a value-equality operator. In this case, it really doesn't matter if two different calls get two different instances because it's very difficult to write code that implicitly depends on them being the same instance.

Also, lazy instantiation is almost always fine:

public Rect Bounds
{
    get
    {
        if (bounds == null)
            bounds = GetBounds(...);
        return bounds;
    }
}

...because subsequent calls will get the same instance, barring any multi-threading problems.

But things can get hairy when a property actually returns a different instance every time, and that instance is a fairly complex and especially mutable object.

For example, let's say you return a Stream:

public Stream OutputStream
{
    get { return new FileStream(...); }
}

This is fairly horrible because someone's very likely to write code like:

foo.OutputStream.Write(data1, 0, data1.Length);
foo.OutputStream.Write(data2, 0, data2.Length);

And depending on exactly how you've implemented OutputStream, one of two nasty things will happen, either there will be a file-locking exception on the second call, if OutputStream always references the same file, or the caller might unintentionally write data to two different files (if, let's say, OutputStream actually creates a new file each time), subsequently corrupting both files.

Don't expect callers to save the return value of a property. They often won't. So if you're considering writing a property that returns a different object each time, make sure that there aren't any serious risks to having two instances floating around at the same time and possibly being swapped or lost.

I've spent many a painful hour debugging code where it looked like everything was working correctly but it turned out I was only working on a copy of the correct instance. Iterators with deferred execution are an especially pernicious subset of this problem; it's not uncommon to foreach through it once and change some property of each element, then foreach through it again and find that everything has "reset"!

One last thing - you should never new up an object that requires cleanup from a property accessor. There's almost no chance at all that the caller will clean it up.