答:
From a software engineering perspective, I believe the proper solution for this kind of problems is in the builder pattern. This is definitely a link from 'guru' authors for your colleague http://en.wikipedia.org/wiki/Builder_pattern.

In the builder pattern, user creates an object that contains the parameters. This parameter container will then be passed into the method. This will take care of any extension and overloading of parameters that your colleague would need in the future while making the whole thing very stable when changes need to be made.

Your example will become:

```<code>public interface IEventGetter {
    public List<FooType> getFooList(ISearchFooRequest req) {
        throws Exception;
    ....
    }
}

public interface ISearchFooRequest {
        public String getName();
        public Date getStart();
        public Date getEnd();
        public int getOffset();
        ...
    }
}

public class SearchFooRequest implements ISearchFooRequest {

    public static SearchFooRequest buildDefaultRequest(String name, Date start) {
        ...
    }

    public String getName() {...}
    public Date getStart() {...}
    ...
    public void setEnd(Date end) {...}
    public void setOffset(int offset) {...}
    ...
}
</code>```

Body:
From a software engineering perspective, I believe the proper solution for this kind of problems is in the builder pattern. This is definitely a link from 'guru' authors for your colleague http://en.wikipedia.org/wiki/Builder_pattern.

In the builder pattern, user creates an object that contains the parameters. This parameter container will then be passed into the method. This will take care of any extension and overloading of parameters that your colleague would need in the future while making the whole thing very stable when changes need to be made.

Your example will become:

public interface IEventGetter {
    public List<FooType> getFooList(ISearchFooRequest req) {
        throws Exception;
    ....
    }
}

public interface ISearchFooRequest {
        public String getName();
        public Date getStart();
        public Date getEnd();
        public int getOffset();
        ...
    }
}

public class SearchFooRequest implements ISearchFooRequest {

    public static SearchFooRequest buildDefaultRequest(String name, Date start) {
        ...
    }

    public String getName() {...}
    public Date getStart() {...}
    ...
    public void setEnd(Date end) {...}
    public void setOffset(int offset) {...}
    ...
}


问:
How do I handle online payment for items with single quantity?
I would like to implement a robust way to handle ecommerce payment for items with limited quantity, like for example exclusive paintings.  Payment would ideally be accepted via PayPal and credit cards.  Ideally, it would work on a 'first-come-first-serve' basis, and wouldn't just lock items out if you add them to cart like some online fashion stores do.

However, the main problem is that once you redirect the user to the payment solution, you do not have control over the user.

Even if I was to implement some form of locking on items, i.e a user adds it to cart and it is temporarily locked for other users for say 30 minutes - I think this problem would still prevail given the below workflow:

User A adds item A with limited quantity (1) to cart.  Item is removed from website for 30 minutes

User A goes to payment on PayPal.

For some reason, UserA does not pay immediately on PayPal but keeps session alive for say 1 hour

After 30 minutes, website will restore item A back in stock

User B adds to cart

User B proceeds to payment

User B pays for item

User A, with the continuously refreshed session, pays for item as well.

This would result in double-purchase for the same item.

Is it possible to solve this problem 100%?  I highly doubt this would happen in real-life, but would like to handle all possible cases.

答:
Usually payment methods involve a step where your application will have to accept the payment. With PayPal it is after the customer is redirected back to your shop. Other PSPs (Payment Service Providers) will have some kind of notification, which you can accept or decline.

At this point you could fulfill the order or decline the fulfillment and the payment.

When choosing a PSP make sure to study the API docs and see if they provide this extra confirmation step.

It would still be not optimal from a customer experience standpoint. But if this is the business model, you would have to communicate very clearly the reasons why orders might not be accepted.

ContentLicense: CC BY-SA 3.0


问:
In Asp.net, how browser knows a textbox is registered with server side TextChanged event?
When I evaluate asp.net control events, I am not able to identify how the browser is aware of asp.net textbox is subscribed to serverside textchanged event or not. When I look the server generated HTML code, there is not information about the TextChanged event.

ASP.Net Declaration

```<code><asp:TextBox ID="txtInput" runat="server" OnTextChanged="txtInput_OnTextChanged"
    AutoPostBack="false" />
</code>```

Server Generated HTML Code

```<code><input name="ctl00$MainContent$txtInput" type="text" value="SivaText Input ChangedText Input Changed.V ChangedText Input Changed.V Changed" id="MainContent_txtInput">
</code>```

答:
ASP.NET generates javascript that attaches to the onchange event causing a postback.

Part of the data sent in the postback/viewdata/viewstate includes what caused the postback with a translation from the client side event to the server side event.

Don't forget - ASP.NET renders normal HTML - on the browser it is just a <textarea> or <input type="text">, after all.


答:
The server encodes the state of all input elements in the hidden field named __VIEWSTATE. Have a look at the rendered HTML and you can see it in the
 element somewhere on the top.

When the form is submitted, both values from the HTML input form elements and the value in the hidden input element __VIEWSTATE are submitted together. For each input element the server compares the values submitted via the corresponding form element (e.g. <input type="text"> with the value encoded in the view state. If they are different, a TextChanged event is triggered for the server-side TextBox control.

Title: In Asp.net, how browser knows a textbox is registered with server side TextChanged event?

Body:
When I evaluate asp.net control events, I am not able to identify how the browser is aware of asp.net textbox is subscribed to serverside textchanged event or not. When I look the server generated HTML code, there is not information about the TextChanged event.

ASP.Net Declaration

```<code><asp:TextBox ID="txtInput" runat="server" OnTextChanged="txtInput_OnTextChanged"
    AutoPostBack="false" />
</code>```

Server Generated HTML Code

```<code><input name="ctl00$MainContent$txtInput" type="text" value="SivaText Input ChangedText Input Changed.V ChangedText Input Changed.V Changed" id="MainContent_txtInput">
</code>```

Body:
The server encodes the state of all input elements in the hidden field named __VIEWSTATE. Have a look at the rendered HTML and you can see it in the <div class="aspNetHidden"> element somewhere on the top.

When the form is submitted, both values from the HTML input form elements and the value in the hidden input element __VIEWSTATE are submitted together. For each input element the server compares the values submitted via the corresponding form element (e.g. <input type="text"> with the value encoded in the view state. If they are different, a TextChanged event is triggered for the server-side TextBox control.


问:
Do you rotate agile team members?
I've got long standing developers in my sprint team. They know the domain, they've been with the company 5+ years and as a team we have a pretty good burn down rate.

There are other sprint teams, some with equally knowledgeable developers and others with newer developers who are trying to get up to speed.

My manager is worried that all our eggs are in one basket and wants to rotate out one or two knowledgeable developers in exchange for the some new guys. I can see their point but can also see the problems that go with that - I'm sure there are others but these are just a few off the top of my head.

New developer will have a much lower work rate

New developer will bring down the work rate of at least one experienced person as they constantly ask questions.

New developer leaves the team at the end to join another team - hopefully he'll remember what he did with us.

New developer leaves the company - wow we wasted a whole bunch of time.

I might like to add that the organisation is struggling with agile. It was a traditional waterfall development company and still thinks in big releases and items that are "expected" to be in the release.

If you've been in a similar situation to this I'd love to know you experiences - does rotating out the team members work? Would pair programming or other methods be a better route to take?

答:
Why should this be all negative?

New people bring new ideas and insights to the group:

New tools

Other ways of working

By having to explain the ways of your team to them, people in your team get challenged:

Why did we decide to do it like this?

Is the reason above still valid?

Explaining stuff to people get people out of their confort zone

And the people joining another team get challenged:

Learn new stuff

Get to know new people

It might change the dynamics in your group, giving other people a boost to take more responsability or a more senior role.

For me rotating can enrich the group as long as the number of developers with technical and domain knowledge in the group is high enough.

Title: Do you rotate agile team members?


问:
Implementing a priority queue with a circular array
[If this fits more to stackoverflow then transfer it there please.]

Hi, I'm trying to implement a priority queue in C.
The easiest way I found to do it is with a circular array (rather than using a linked list).
I have an array of fixed size, the index for the first element in the queue and the index for the next free place in the queue.
But I'm struggling with dequing the maximum value...
I know how to get the maximum value, but not how to move next and first so that the queue stays contiguous in the array (the only way I know of it working).

How should I do this? Or do you have a suggestion for a better implementation?

Thanks

答:
Don't use a circular array at all.  It's way simpler and more efficient to just use a regular array where you fill gaps by swapping with the backmost value of the array, and only manipulate the end index when you add or remove elements.

As said by others, a binary heap is the standard way to implement a priority queue, and you will benefit from this same overwrite-to-remove strategy when implementing a binary heap.

```<code>push (int i) {
  // Make sure it's not full first!
  array[end_index++] = i;
}

int pop () {
  // Make sure it's not empty first!
  // Set max_index to index the maximum value
  int result = array[max_index];
  array[max_index] = array[--end_index];
}
</code>```

Body:
Don't use a circular array at all.  It's way simpler and more efficient to just use a regular array where you fill gaps by swapping with the backmost value of the array, and only manipulate the end index when you add or remove elements.

As said by others, a binary heap is the standard way to implement a priority queue, and you will benefit from this same overwrite-to-remove strategy when implementing a binary heap.

push (int i) {
  // Make sure it's not full first!
  array[end_index++] = i;
}

int pop () {
  // Make sure it's not empty first!
  // Set max_index to index the maximum value
  int result = array[max_index];
  array[max_index] = array[--end_index];
}


问:
Is it ok to start with templates in MVC development?
I'm new to web development and I've started working on a project in my company that uses DJANGO. I feel it flexible to start my development straight first from the templates. I think it will be easier if I visualize things first. So my question: Is it okay to start with a template rather than starting with models first? Will I stumble on to any sort of confusions if I go by this method of development? </p>

答:
There is no right answer. You will probably be going back and forth between models and templates before you settle on something which works.

You should start of with use-cases or usage scenarios which include the view templates. As you write those, you will expose some system concepts, many of which will become your core models. Once you see what is possible with your models, you may realize that you have more use-cases which can take advantage of the models. Or you may discover that your models have complex relationships which  will lead you to refactoring the models. And that could lead you to more use-cases. And so on...Eventually, you'll run out of use-cases, and your model will be just right, assuming that you have normalized them.

When you do your use-cases, you have to expose a minimal subset of models to your users. Make sure that you understand which models are exposed and which ones are not exposed.


问:
Multiple intranet/internet systems partially working on same data - database strategy
We are starting rewritting our apps (Internet portal, millions of unique users and few CRM/ERP systems, few hundred users) and we have a huge decision to make now. We are going to write them mostly (90-95%) in Symfony2 with Doctrine, and some background services (e.g. mailing) in Java. Database - MySql/MariaDb. also lot of additional technologies (redis/memcached, load balancing, varnish, replication and so on). Most important (in this case) are - symfony2, mysql/maria and doctrine.

The thing is - it will be best for few systems to work on same tables. For example: internet portal with job offers + CRM system for managing clients that pay for posting those offers (there are many similar cases). Also having functionality of one login for our users between every system is important.

I see two approaches here:

We have one big database, having few hundred of tables. I used to work with 200+ tables, but not with that high amount of traffic. So if traffic goes up, sharding/partitioning will be involved.

We have many databases, each for one app. If there is need for one app to communicate with another DB, we will write special services to deliver that functionality.

Now, what I'm worried about:
1. ease of development - it's easier to just have one database
2. ease of configuration/assuring redudancy
3. performance

One thing I know now that database will be hosted on three machines with master-slave replication, which is supported nicely by Doctrine.

What are your thoughts? What are your pro's and con's? Thanks!

答:
1 Database, mirrored and clustered and partitioned as required and serving stored procedures as an API to:

A couple of App servers, that talk to the the DB and provide a domain-neutral API to:

Many web servers that clients interact with.

This is the way to achieve scalability. You offset some processing to the tiers, so web servers handle all the presentation of the html pages, given data that has been retrieved from the DB and combined or otherwise massaged into shape by the application tiers. Generally this scales well horizontally (ie need more scale, add more web or app servers).

The load on the DB can be reduced with this architecture - the DB solely serves raw data to the app tiers. This means the app tier can provide caching of some data to further reduce the load on the DB, as there's only a few of them you don't need a full-on caching mechanism to keep the caches in sync.

You can also introduce separate DBs if the data is easily partitioned and the clients wouldn't even know you've done it as they talk to the app tier. This is probably the biggest win, you can change things without re-deploying everything.


问:
Why can't C arrays have 0 length?
The C11 standard says the arrays, both sized and variable length "shall have a value greater than zero."  What is the justification for not allowing a length of 0?

Especially for variable length arrays it makes perfect sense to have a size of zero every once and a while.  It is also useful for static arrays when their size is from a macro or build configuration option.

Interestingly GCC (and clang) provide extensions that allow zero length arrays.  Java also allows arrays of length zero.

答:
Let's look at how an array is typically laid out in memory:

```<code>         +----+
arr[0] : |    |
         +----+
arr[1] : |    |
         +----+
arr[2] : |    |
         +----+
          ...
         +----+
arr[n] : |    |
         +----+
</code>```

Note that there isn't a separate object named arr that stores the address of the first element; when an array appears in an expression, C computes the address of the first element as needed.

So, let's think about this: a 0-element array would have no storage set aside for it, meaning there's nothing to compute the array address from (put another way, there's no object mapping for the identifier).  It's like saying, "I want to create an int variable that takes up no memory."  It's a nonsensical operation.

Edit

Java arrays are completely different animals from C and C++ arrays; they're not a primitive type, but a reference type derived from Object.

Edit2

A point brought up in the comments below - the "greater than 0" constraint only applies to arrays where the size is specified through a constant expression; a VLA is allowed to have a 0 length Declaring a VLA with a 0-valued non-constant expression is not a constraint violation, but it does invoke undefined behavior.

It's clear that VLAs are different animals from regular arrays, and their implementation can allow for a 0 size.  They cannot be declared static or at file scope, because the size of such objects must be known before the program starts.

It's also worth nothing that as of C11, implementations are not required to support VLAs.

Title: Why can't C arrays have 0 length?

Body:
Let's look at how an array is typically laid out in memory:

         +----+
arr[0] : |    |
         +----+
arr[1] : |    |
         +----+
arr[2] : |    |
         +----+
          ...
         +----+
arr[n] : |    |
         +----+

Note that there isn't a separate object named arr that stores the address of the first element; when an array appears in an expression, C computes the address of the first element as needed.

So, let's think about this: a 0-element array would have no storage set aside for it, meaning there's nothing to compute the array address from (put another way, there's no object mapping for the identifier).  It's like saying, "I want to create an int variable that takes up no memory."  It's a nonsensical operation.

Edit

Java arrays are completely different animals from C and C++ arrays; they're not a primitive type, but a reference type derived from Object.

Edit2

A point brought up in the comments below - the "greater than 0" constraint only applies to arrays where the size is specified through a constant expression; a VLA is allowed to have a 0 length Declaring a VLA with a 0-valued non-constant expression is not a constraint violation, but it does invoke undefined behavior.

It's clear that VLAs are different animals from regular arrays, and their implementation can allow for a 0 size.  They cannot be declared static or at file scope, because the size of such objects must be known before the program starts.

It's also worth nothing that as of C11, implementations are not required to support VLAs.


问:
Assigning strings to pointer in C
My question is about pointers in C. As far as I've learned and searched, pointers can only store addresses of other variables, but cannot store the actual values (like integers or characters). But in the code below the char pointer c actually storing a string. It executes without errors and give the output as 'name'.

```<code>#include <stdio.h>
main()
{
  char *c;
  c="name";
  puts(c);
}
</code>```

Can anyone explain how a pointer is storing a string without any memory or if memory is created where it is created and how much size it can be created?

I tried using it with the integer type pointer

```<code>#include <stdio.h>
main()
{
  int *c;
  c=10;
  printf("%d",c);
}
</code>```

but it gave an error

```<code>cc     test.c   -o test
test.c: In function ‘main’:
test.c:5:3: warning: assignment makes pointer from integer without a cast   [enabled by default]
c=10;
^
test.c:6:2: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int *’ [-Wformat=]
printf("%d",c);
^
</code>```

Pointers stores the address of variable then why is integer pointer different from character pointer?

Is there something I am missing?

答:
String literals like "name" are stored as arrays of char (const char in C++) such that they are allocated when the program starts and held until the program terminates.

The type of the expression "name" is "5-element array of char" (5th element for the 0 terminator).  Except when it is the operand of the sizeof or unary * operators, or is a string literal being used to initialize an array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

So, when you write

```<code>c="name";
</code>```

"name" is not the operand of the sizeof or unary * operators, and it isn't being used to initialize an array in a declaration, so the address of the first element of the string is being assigned to the pointer variable c.  Essentially, what you have in memory is something like the following:

```<code>            +-----+
"name"[0] : | 'n' |  <-------+
            +-----+          |
"name"[1] : | 'a' |          |
            +-----+          |
"name"[2] : | 'm' |          |
            +-----+          |
"name"[3] : | 'e' |          |
            +-----+          |
"name"[4] : |  0  |          |
            +-----+          |
              ...            |
            +-----+          |
        c : |     | ---------+
            +-----+
</code>```

Title: Assigning strings to pointer in C

Body:
String literals like "name" are stored as arrays of char (const char in C++) such that they are allocated when the program starts and held until the program terminates.

The type of the expression "name" is "5-element array of char" (5th element for the 0 terminator).  Except when it is the operand of the sizeof or unary * operators, or is a string literal being used to initialize an array in a declaration, an expression of type "N-element array of T" will be converted ("decay") to an expression of type "pointer to T", and the value of the expression will be the address of the first element of the array.

So, when you write

c="name";

"name" is not the operand of the sizeof or unary * operators, and it isn't being used to initialize an array in a declaration, so the address of the first element of the string is being assigned to the pointer variable c.  Essentially, what you have in memory is something like the following:

            +-----+
"name"[0] : | 'n' |  <-------+
            +-----+          |
"name"[1] : | 'a' |          |
            +-----+          |
"name"[2] : | 'm' |          |
            +-----+          |
"name"[3] : | 'e' |          |
            +-----+          |
"name"[4] : |  0  |          |
            +-----+          |
              ...            |
            +-----+          |
        c : |     | ---------+
            +-----+


问:
Is there a better way to load objects?
I have always kept the code to load an object within the object itself. That way no matter what method is creating the object, it always has access to the method to load the object. However this does mean that if I'm loading a lot of objects I have to create a blank copy of an object to retrieve an array of objects, and it doesn't seem to be the most logical way of loading an array of objects. Take this code as an example, a page is loading a bunch of products.

```<code>class Product() {

    // product variables...

    public function LoadProducts($dbConn, $where) {
        $products = array();
        $query = "SELECT * FROM products $where";
        $results = $dbConn->query($query);
        while($row = $results->fetch_assoc()) {
            $products[$row['pId']] = new Product();
            $products[$row['pId']]->StoreVars($row);
        }
        return $products;
    }

    public function StoreVars($row) {
        foreach($row as $key => $val) {
            $this->$key = $val;
        }
    }

}

class Page() {

    // page variables...

    public function DrawPage($dbConn) {
        $product = new Product();
        $where = "Some where clause";
        $products = $product->LoadProducts($dbConn, $where);
        // Do something with products to output HTML to the page...
    }

}
</code>```

Most of my objects like product follow a similar pattern. Is this good practice? Is there different / a standard way of doing this? Am I doing this correctly? It just seems a bit pointless to me to have to call a blank instance of product to load all the products, but I don't know where else to put that function so I don't have to have many copies of the same query.

答:
You might consider making LoadProducts() a static method, so that you don't have to instantiate a blank object to load a product list:

```<code>class Product {
   public static function LoadProducts(...)
   {
   }
}
</code>```

and then its just

```<code>$products = Product::LoadProducts( ...)
</code>```

Title: Is there a better way to load objects?

Body:
You might consider making LoadProducts() a static method, so that you don't have to instantiate a blank object to load a product list:

class Product {
   public static function LoadProducts(...)
   {
   }
}

and then its just

$products = Product::LoadProducts( ...)


问:
Programming for future use of interfaces
I have a colleague sitting next to me who designed an interface like this:

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

The problem is, right now, we are not using this "end" parameter anywhere in our code, it's just there because we might have to use it some time in the future.

We are trying to convince him it's a bad idea to put parameters into interfaces that are of no use right now, but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

Now, my question is, are there any sources that are handling a topic like this of "respected" coding gurus that we can link him to?

答:
You don't need it now, so don't add it.  If you need it later, extend the interface:</p>

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start)
         throws Exception;
    ....

}

public interface IBoundedEventGetter extends IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

OwnerDisplayName: sveri

Body:
You don't need it now, so don't add it.  If you need it later, extend the interface:

public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start)
         throws Exception;
    ....

}

public interface IBoundedEventGetter extends IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}


问:
Desktop to Web - How to deal with user-interactive workflows
I start a new project this summer, consisting in developing a web version of a proprietary desktop ERP.

The main goal of my company is to be able to propose a web version of its ERP, with all advantages it involves (mobility, possibility of selling SaaS versions, modern look and components ...), without losing any business feature.  By this, I mean that us developers can't rework the business side of the app. The main goal is to be able to translate same processes into web application.

Business layer of the older version is not directly reusable, since it's really GUI-dependent. Those business process were rewritten as UML diagrams, which will be used as support for us to develop the new app.

The problem I meet is that I don't know how to deal with process that need user interactions. For example :

On validation of a sale order, the validation process checks all products it contains, verifying if there is available stock, and then perform different operations. If there is no stock available, the user is asked if he wants to cancel the order, remove this product or select another one equivalent. It works like a Javascript alert or confirm : current "thread" (ie validation process) is on hold, waiting for user interaction. After user's choice, it finishes dealing with the current product, and then validates the next one, and so on.

How to deal with this kind of processes with a web application ? Is there some framework, design pattern or something else that permits to write this kind of business processes, able to start and hold like that ?

A solution could be to split those business processes into smaller ones. For my example, we would have 2 sub-processes : the first one checks all products and flags the problematic ones. Then the user has a screen to decide what to do on flagged products, and validates. At this moment we are sure all products are OK, we can start the second sub-process to perform the others operations.

The problem with it is that even if it's pretty simple on this example, it can be really more complicated. Some process have a lot of users interactions like this one, and then could be splitted into 10 subparts. Like I earlier precised, we don't want to modify or rethink business process, to be sure that we lose nothing or introduce new business bugs.

Does someone has an experience about it ? Do you know some way to deal with this kind of desktop-to-web developments ?

EDIT 15/07/14

There was some misunderstanding about this post, surely related to my poor english expression and vocabulary.

To summarize the problem :

I got a bunch of business workflows described into UML diagrams. They comes from a huge 30-year-old CAMM (production management ERP). The project is to redevelop this application under Java web environment.
The main point is that some of those workflows are user-dependent, since, in the middle of the processing, they need a user-interaction. Because web applications are based on a client-server architecture, I don't know how to port them.
Reworking/rethinking these workflows is not an option, because it would be too much time-consuming. I need a way to simulate a desktop application on a web app, like Wt, but for Java (i'm not talking about UI but about how to develop workflows ), or to define rules to make those user-dependent workflows web-compatibles.

答:
Your primary difficulties I feel are that you have a mismatch between a very linear and custom workflow in an older application that do not coincide with the user interaction workflows that are common on the web.

Web applications that interact with a server application that contain the business logic communicate in a Request/Response messaging style.  The client browser and the server running an application that has the business logic are separate processes.  The client requests a resource (html page, jpg image, JSON data, etc...) and the server provides that resource in an inherently stateless way.  This is a much different paradigm from your self contained desktop application that has a concept of global state for a users session.  The users session in a desktop application lives and dies by the running process on the workstation.

So basically there are two ways you can handle the maintenance of state in a web application that always has a client/server relationship.

Server Centric

A server centric web application will maintain stateful information for an individual user's session.  They do this typically by serving a session cookie once the user is authenticated.  The client application (browser) will include its unique session token with each request which allows the server to retrieve stateful information about the clients state from the last time they received a request for this client.

Further the server will contain most if not all of the business logic behind performing actions that the typical business user will want to achieve, actions that have real business value.  This is not to be confused with presentation logic which is most client side code (Eg. Javascript) that performs user interface interaction like hiding a particular menu in a form if a specific checkbox has been checked.

Client Centric

While you might have a server to maintain authentication of a user and maintaing an active session, you could use a client side scripting framework (Eg. Javascript framework like AngularJS to perform most if not all of the business logic operations and presentation logic operations.  The advantages of this model are that you can program your web application in much the same way as one might program a desktop application.  Client state will live and die by the browser navigation to the current page in much the same way that it will live and die on the running process of a desktop application.  For communication with a database you can expose stateless webservices on the server that can proxy for a database.

Some important considerations with this approach are that users on client browsers have the ability to modify or change how Javascript can behave which might be potentially dangerous and introduce unknown exception cases to your application.  It is highly recommended that if this approach is taken that great care should be taken on interactions with servers to sanitize inputs and validate all data going back and forth.

Summary

In summary, the application you specified is very old. It sounds like you are making the right choice in capturing the current workflows and trying to assess what the user needs are.  The next step would be to try and follow Agile principles and capture business value in user stories.  I would start on clean slate and try to discover other means and workflows that can also attain the same business value captured in the user stories.  This application is so old that it was likely limited by the technology of its day to where technical constraints influenced the user workflows in a negative or archaic way.  Basically there are probably better ways, more intuitive workflows and user interfaces that the business can use that will also achieve the same end goals.


答:
No design principle is absolute, so while I mostly agree with the other answers, I thought I'd play devil's advocate and discuss some conditions under which I would consider accepting your colleague's solution:

If this is a public API, and you anticipate the feature being useful to third-party developers, even if you don't use it internally.

If it has considerable immediate benefits, not just future ones.  If the implied end date is Now(), then adding a parameter removes a side effect, which has benefits for caching and unit testing.  Maybe it allows for a simpler implementation.  Or maybe it is more consistent with other APIs in your code.

If your development culture has a problematic history.  If processes or territoriality make it too difficult to change something central like an interface, then what I've seen happen before is people implementing client-side workarounds instead of changing the interface, then you're trying to maintain a dozen ad hoc end date filters instead of one.  If that sort of thing happens a lot at your company, it makes sense to put a little more effort into future proofing.  Don't get me wrong, it's better to change your development processes, but this is usually easier said than done.

That being said, in my experience the biggest corollary to YAGNI is YDKWFYN: You Don't Know What Form You'll Need (yes, I just made that acronym up).  Even if needing some limit parameter might be relatively predictable, it might take the form of a page limit, or number of days, or a boolean specifying to use the end date from a user preferences table, or any number of things.

Since you don't have the requirement yet, you have no way of knowing what type that parameter should be.  You often end up either having an awkward interface that isn't quite the best fit for your requirement, or having to change it anyway.

Title: Programming for future use of interfaces

Body:
I have a colleague sitting next to me who designed an interface like this:

```<code>public interface IEventGetter {

    public List<FooType> getFooList(String fooName, Date start, Date end)
        throws Exception;
    ....

}
</code>```

The problem is, right now, we are not using this "end" parameter anywhere in our code, it's just there because we might have to use it some time in the future.

We are trying to convince him it's a bad idea to put parameters into interfaces that are of no use right now, but he keeps on insisting that a lot of work will have to be done if we implement the use of "end" date some time later and have to adapt all the code then.

Now, my question is, are there any sources that are handling a topic like this of "respected" coding gurus that we can link him to?


问:
What would truly happen if java.lang.String weren't final?
I'm a long time Java developer and finally, after majoring, I have time to study it decently in order to take the certification exam... One thing that has always bothered me is String being "final". I do understand it when a read about the security issues and related stuff... But, seriously, does anyone have a true example of that?

For instance, what would happen if String weren't final? Like it's not in Ruby. I haven't heard any complaints coming from the Ruby community... And I'm aware of the StringUtils and related classes that you have to either implement yourself or search over the web to just implement that behavior (4 lines of code) you're willing to.

答:
Background

There are three places where final can show up in Java:

Classes (JLS 8.1.1.2)

Methods (JLS 8.4.3.3)

Fields (JLS 8.3.1.2)

Making a class final prevents all subclassing of the class.  Making a method final prevents subclasses of the method from overriding it.  Making a field final prevents it from being changed later.

Misconceptions

There are optimizations that happen around final methods and fields.

A final method makes it easier for HotSpot to optimize via inlining.  However, HotSpot does this even if the method isn't final as it works on the assumption that it hasn't been overridden until proven otherwise. More about this on SO

A final variable can be aggressively optimized, and more about that can be read in the JLS section 17.5.3.

However, with that understanding one should be aware that neither of these optimizations are about making a class final.  There is no performance gain by making a class final.

The final aspect of a class has nothing to do with immutability either.  One can have an immutable class (such as BigInteger) that is not final, or a class that is mutable and final (such as StringBuilder).  The decision about if a class should be final is a question of design.

Final Design

Strings are one of the most used data types.  They are found as keys to maps, they store user names and passwords, they are what you read in from a keyboard or a field on a web page.  Strings are everywhere.

Maps

The first thing to consider of what would happen if you could subclass String is realizing that someone could construct a mutable String class that would appear to otherwise be a String.  This would mess up Maps everywhere.

Consider this hypothetical code:

```<code>Map t = new TreeMap<String, Integer>();
Map h = new HashMap<String, Integer>();
MyString one = new MyString("one");
MyString two = new MyString("two");

t.put(one, 1); h.put(one, 1);
t.put(two, 2); h.put(two, 2);

one.prepend("z");
</code>```

This is a problem with using a mutable key in general with a Map, but the thing that I'm trying to get at there is that suddenly a number of things about the Map break.  The Entry is no longer at the right spot in the map.  In a HashMap, the hash value has (should have) changed and thus its no longer at the right entry.  In the TreeMap, the tree is now broken because one of the nodes is on the wrong side.

Since using a String for these keys is so common, this behavior should be prevented by making the String final.

You may be interested in reading Why is String immutable in Java? for more about the immutable nature of Strings.

Nefarious strings

There are a number of various nefarious options for Strings.  Consider if I made a String that always returned true when equal was called... and passed that into a password check?  Or made it so that assignments to MyString would send a copy of the String to some email address?

These are very real possibilities when you have the ability to subclass String.

Java.lang String optimizations

While before I mentioned that final doesn't make String faster.  However, the String class (and other classes in java.lang) make frequent use of package level protection of fields and methods to allow other java.lang classes to be able to tinker with the internals rather than going through the public API for String all the time.  Functions like getChars without range checking or lastIndexOf that is used by StringBuffer, or the constructor that shares the underlying array (note that thats a Java 6 thing that was changed because of memory issues).

If someone made a subclass of String, it wouldn't be able to share those optimizations (unless it was part of java.lang too, but that's a sealed package).

Its harder to design something for extension

Designing something to be extendable is hard.  It means that you've got to expose parts of your internals for something else to be able to modify.

An extendable String could not have had its memory leak fixed.  Those parts of it would need to have been exposed to subclasses and changing that code would then mean the subclasses would break.

Java prides itself in backwards compatibility and by opening up core classes to extension, one loses some of that ability to fix things while still maintaining the computability with third party subclasses.

Checkstyle has a rule that it enforces (that really frustrates me when writing internal code) called "DesignForExtension" which enforces that every class is either:

Abstract

Final

Empty implementation

The rational for which is:

This API design style protects superclasses against being broken by subclasses. The downside is that subclasses are limited in their flexibility, in particular they cannot prevent execution of code in the superclass, but that also means that subclasses cannot corrupt the state of the superclass by forgetting to call the super method.

Allowing implementation classes to be extended means that the subclasses can possibly corrupt the state of the class it is based off of and make it so that various guarantees that the superclass gives are invalid.  For something as complex as String, it is almost a certainty that changing part of it will break something.

Developer hurbis

Its part of being a developer. Consider the likelihood that each developer will create their own String subclass with their own collection of utils in it.  But now these subclasses cannot be freely assigned back to each other.

```<code>WleaoString foo = new WleaoString("foo");
MichaelTString bar = foo; // This doesn't work.
</code>```

This way leads to madness. Casting to String all over the place and checking to see if the String is an instance of your String class or if not, making a new String based on that one and... just, no.  Don't.

I'm sure you can write a good String class... but leave writing multiple string implementations to those crazy people who write C++ and have to deal with std::string and char* and something from boost and SString, and all the rest.

Java String magic

There are several magical things that Java does with Strings.  These make it easier for a programmer to deal with but introduce some inconsistencies in the language.  Allowing subclasses on String would take some very significant thought about how to deal with these magical things:

String Literals (JLS 3.10.5)

Having code that allows one to do:

```<code>String foo = "foo";
</code>```

This is not to be confused with boxing of the numeric types like Integer.  You can't do 1.toString(), but you can do "foo".concat(bar).

The + operator (JLS 15.18.1)

No other reference type in Java allows for an operator to be used on it.  The String is special.  The string concatenation operator also works at the compiler level so that "foo" + "bar" becomes "foobar" when it is compiled rather than at runtime.

String Conversion (JLS 5.1.11)

All objects can be converted into Strings just by using them in a String context.

String Interning (JavaDoc)

The String class has access to the pool of Strings that allow it to have canonical representations of the object which is populated at compile type with the String literals.

Allowing a subclass of String would mean that these bits with the String that make it easier to program would become very difficult or impossible to do when other String types are possible.

Body:
Background

There are three places where final can show up in Java:

Classes (JLS 8.1.1.2)

Methods (JLS 8.4.3.3)

Fields (JLS 8.3.1.2)

Making a class final prevents all subclassing of the class.  Making a method final prevents subclasses of the method from overriding it.  Making a field final prevents it from being changed later.

Misconceptions

There are optimizations that happen around final methods and fields.

A final method makes it easier for HotSpot to optimize via inlining.  However, HotSpot does this even if the method isn't final as it works on the assumption that it hasn't been overridden until proven otherwise. More about this on SO

A final variable can be aggressively optimized, and more about that can be read in the JLS section 17.5.3.

However, with that understanding one should be aware that neither of these optimizations are about making a class final.  There is no performance gain by making a class final.

The final aspect of a class has nothing to do with immutability either.  One can have an immutable class (such as BigInteger) that is not final, or a class that is mutable and final (such as StringBuilder).  The decision about if a class should be final is a question of design.

Final Design

Strings are one of the most used data types.  They are found as keys to maps, they store user names and passwords, they are what you read in from a keyboard or a field on a web page.  Strings are everywhere.

Maps

The first thing to consider of what would happen if you could subclass String is realizing that someone could construct a mutable String class that would appear to otherwise be a String.  This would mess up Maps everywhere.

Consider this hypothetical code:

Map t = new TreeMap<String, Integer>();
Map h = new HashMap<String, Integer>();
MyString one = new MyString("one");
MyString two = new MyString("two");

t.put(one, 1); h.put(one, 1);
t.put(two, 2); h.put(two, 2);

one.prepend("z");

This is a problem with using a mutable key in general with a Map, but the thing that I'm trying to get at there is that suddenly a number of things about the Map break.  The Entry is no longer at the right spot in the map.  In a HashMap, the hash value has (should have) changed and thus its no longer at the right entry.  In the TreeMap, the tree is now broken because one of the nodes is on the wrong side.

Since using a String for these keys is so common, this behavior should be prevented by making the String final.

You may be interested in reading Why is String immutable in Java? for more about the immutable nature of Strings.

Nefarious strings

There are a number of various nefarious options for Strings.  Consider if I made a String that always returned true when equal was called... and passed that into a password check?  Or made it so that assignments to MyString would send a copy of the String to some email address?

These are very real possibilities when you have the ability to subclass String.

Java.lang String optimizations

While before I mentioned that final doesn't make String faster.  However, the String class (and other classes in java.lang) make frequent use of package level protection of fields and methods to allow other java.lang classes to be able to tinker with the internals rather than going through the public API for String all the time.  Functions like getChars without range checking or lastIndexOf that is used by StringBuffer, or the constructor that shares the underlying array (note that thats a Java 6 thing that was changed because of memory issues).

If someone made a subclass of String, it wouldn't be able to share those optimizations (unless it was part of java.lang too, but that's a sealed package).

Its harder to design something for extension

Designing something to be extendable is hard.  It means that you've got to expose parts of your internals for something else to be able to modify.

An extendable String could not have had its memory leak fixed.  Those parts of it would need to have been exposed to subclasses and changing that code would then mean the subclasses would break.

Java prides itself in backwards compatibility and by opening up core classes to extension, one loses some of that ability to fix things while still maintaining the computability with third party subclasses.

Checkstyle has a rule that it enforces (that really frustrates me when writing internal code) called "DesignForExtension" which enforces that every class is either:

Abstract

Final

Empty implementation

The rational for which is:

This API design style protects superclasses against being broken by subclasses. The downside is that subclasses are limited in their flexibility, in particular they cannot prevent execution of code in the superclass, but that also means that subclasses cannot corrupt the state of the superclass by forgetting to call the super method.

Allowing implementation classes to be extended means that the subclasses can possibly corrupt the state of the class it is based off of and make it so that various guarantees that the superclass gives are invalid.  For something as complex as String, it is almost a certainty that changing part of it will break something.

Developer hurbis

Its part of being a developer. Consider the likelihood that each developer will create their own String subclass with their own collection of utils in it.  But now these subclasses cannot be freely assigned back to each other.

WleaoString foo = new WleaoString("foo");
MichaelTString bar = foo; // This doesn't work.

This way leads to madness. Casting to String all over the place and checking to see if the String is an instance of your String class or if not, making a new String based on that one and... just, no.  Don't.

I'm sure you can write a good String class... but leave writing multiple string implementations to those crazy people who write C++ and have to deal with std::string and char* and something from boost and SString, and all the rest.

Java String magic

There are several magical things that Java does with Strings.  These make it easier for a programmer to deal with but introduce some inconsistencies in the language.  Allowing subclasses on String would take some very significant thought about how to deal with these magical things:

String Literals (JLS 3.10.5)

Having code that allows one to do:

String foo = "foo";

This is not to be confused with boxing of the numeric types like Integer.  You can't do 1.toString(), but you can do "foo".concat(bar).

The + operator (JLS 15.18.1)

No other reference type in Java allows for an operator to be used on it.  The String is special.  The string concatenation operator also works at the compiler level so that "foo" + "bar" becomes "foobar" when it is compiled rather than at runtime.

String Conversion (JLS 5.1.11)

All objects can be converted into Strings just by using them in a String context.

String Interning (JavaDoc)

The String class has access to the pool of Strings that allow it to have canonical representations of the object which is populated at compile type with the String literals.

Allowing a subclass of String would mean that these bits with the String that make it easier to program would become very difficult or impossible to do when other String types are possible.


答:
You would usually want your zero (in fact variable) size array to know its size at run time. Then pack that in a struct and use flexible array members, like e.g.:

```<code>struct my_st {
   unsigned len;
   double flexarray[]; // of size len
};
</code>```

Obviously the flexible array member has to be the last in its struct and you need to have something before. Often that would be something related to the actual runtime-occupied length of that flexible array member.

Of course you would allocate:

```<code> unsigned len = some_length_computation();
 struct my_st*p = malloc(sizeof(struct my_st)+len*sizeof(double));
 if (!p) { perror("malloc my_st"); exit(EXIT_FAILURE); };
 p->len = len;
 for (unsigned ix=0; ix<len; ix++)
    p->flexarray[ix] = log(3.0+(double)ix);
</code>```

AFAIK, this was already possible in C99, and it is very useful.

BTW, flexible array members don't exist in C++ (because it would be difficult to define when and how they should be constructed & destructed). See however the future std::dynarray

Title: Why can't C arrays have 0 length?

Body:
The C11 standard says the arrays, both sized and variable length "shall have a value greater than zero."  What is the justification for not allowing a length of 0?

Especially for variable length arrays it makes perfect sense to have a size of zero every once and a while.  It is also useful for static arrays when their size is from a macro or build configuration option.

Interestingly GCC (and clang) provide extensions that allow zero length arrays.  Java also allows arrays of length zero.

Body:
You would usually want your zero (in fact variable) size array to know its size at run time. Then pack that in a struct and use flexible array members, like e.g.:

struct my_st {
   unsigned len;
   double flexarray[]; // of size len
};

Obviously the flexible array member has to be the last in its struct and you need to have something before. Often that would be something related to the actual runtime-occupied length of that flexible array member.

Of course you would allocate:

 unsigned len = some_length_computation();
 struct my_st*p = malloc(sizeof(struct my_st)+len*sizeof(double));
 if (!p) { perror("malloc my_st"); exit(EXIT_FAILURE); };
 p->len = len;
 for (unsigned ix=0; ix<len; ix++)
    p->flexarray[ix] = log(3.0+(double)ix);

AFAIK, this was already possible in C99, and it is very useful.

BTW, flexible array members don't exist in C++ (because it would be difficult to define when and how they should be constructed & destructed). See however the future std::dynarray


答: Using a static method as GrandmasterB suggested is definitely a step in the right direction, but I think you shouldn't have code for loading in this class at all. You should try to follow the Single Responsibility Principle and make your classes as focused, independent and modular as possible, so you don't want to tie them to a certain implementation for loading them. Decoupling classes from their context makes them more robust, more flexible and easier to test.</p>

Title: Is there a better way to load objects?

Body:
I have always kept the code to load an object within the object itself. That way no matter what method is creating the object, it always has access to the method to load the object. However this does mean that if I'm loading a lot of objects I have to create a blank copy of an object to retrieve an array of objects, and it doesn't seem to be the most logical way of loading an array of objects. Take this code as an example, a page is loading a bunch of products.

```<code>class Product() {

    // product variables...

    public function LoadProducts($dbConn, $where) {
        $products = array();
        $query = "SELECT * FROM products $where";
        $results = $dbConn->query($query);
        while($row = $results->fetch_assoc()) {
            $products[$row['pId']] = new Product();
            $products[$row['pId']]->StoreVars($row);
        }
        return $products;
    }

    public function StoreVars($row) {
        foreach($row as $key => $val) {
            $this->$key = $val;
        }
    }

}

class Page() {

    // page variables...

    public function DrawPage($dbConn) {
        $product = new Product();
        $where = "Some where clause";
        $products = $product->LoadProducts($dbConn, $where);
        // Do something with products to output HTML to the page...
    }

}
</code>```

Most of my objects like product follow a similar pattern. Is this good practice? Is there different / a standard way of doing this? Am I doing this correctly? It just seems a bit pointless to me to have to call a blank instance of product to load all the products, but I don't know where else to put that function so I don't have to have many copies of the same query.


问:
What kind of exception to ask for out of range arguments?
What type of exception should I throw?

I have a console class which describes rectangle of cells which a user can index by passing in a coordinate:

```<code>width, height = 80, 25
console = Console.new(width, height)

x, y = 2, 5
point_on_screen = Point.new(x, y)
console[point_on_screen] = 'a'
</code>```

I am now wondering what types of exception to throw when an index occurs out of bounds . That is, outside of the (constant!) domains x:[0, width] and y:[0, height]. I could throw a RangeError or an ArgumentError *.

Does it matter which type of exception to throw as long as the error message is useful?

Should I use the same exception type for both the construction of the console and the indexing? Are the two really semantically different?

* returning a kind of out of bounds object is possibly a better option - something like a Null Object Pattern - but not what I am wondering about here.

ArgumentError

One option is to throw an ArgumentError because the argument is obviously wrong, dimensions can never be non-negative. This is what I throw in example 1, because we ought to know in advance that the dimensions should be non-negative.

Example 1:

```<code>console = Console new(-3, 4) # Argument error
</code>```

RangeError

Another option is to throw a RangeError because the argument is out of the valid range. I use these for indexing. The argument is always out of range if x < 0, but if x ≥ 0 then it depends on the width of the console if the x is in the domain.

Example 2:

```<code>console = Console.new(20, 40)
pt = Point.new(-3, 4)
Console[pt] # RangeError
</code>```

答:
You could always create a custom exception if you dont find the exceptions you have at your disposal fit correctly.</p>

```<code>class MyUsefulException < Exception
end

raise MyUsefulException, 'Huzzah, my exception lives!!!'
</code>```

OwnerDisplayName: R. Peereboom

Body:
You could always create a custom exception if you dont find the exceptions you have at your disposal fit correctly.

class MyUsefulException < Exception
end

raise MyUsefulException, 'Huzzah, my exception lives!!!'


问:
Traverse a matrix using a linear index to get an evenly distributed values sample
I'm looking for an algorithm idea on how to traverse a matrix using a linear index while avoiding row/column based traversals to get a more diverse distribution of values.

To understand this better, think of an image that's split in blocks, with N rows & M columns. I need to process each image block sequentially (from 1 to NxM) but I don't know in advance what the processing time will be for each block ( blocks that are close together tend to have a similar processing time, with small variations).

During processing, I need to be able to estimate as best as possible the remaining processing time based on the number of blocks that have already been processed & their associated processing time. For this reason, traversing the blocks by columns or by rows will not give an accurate estimation so I need to find another way of traversing the matrix that would pick values from different zones of the image.

It's also important to be able to determine the blocks processing order based on a linear index (from 1 to NxM), without calculating them in advance. The algorithm that returns the row & column corresponding to the linear index should be as fast as possible.

Shorter version of the question

For a liner index named idx, I need to get a corresponding row & column pair from a matrix with N rows & M columns while avoiding a row/column based traversal.

For each idx between 1 and NxM, the algorithm would return a [row, column] pair so that all the rows & columns combinations are returned exactly once.

Example

(the values in the matrix represent the linear index's value that's associated with that row&column position)

```
 1 17 13  9  5
 6  2 18 14 10
11  7  3 19 15
16 12  8  4 20
```

The above example is for a diagonal traversal that would produce a better distribution of values that a row/column based traversal.

Another possible solution would be to split the matrix into smaller blocks & traverse those blocks in rows/columns. For example a 4x5 matrix could be virtually split into 2x2 blocks and those smaller blocks could be traversed by rows or columns (e.g. idx(1) = block1[1, 1], idx(2) = block2[1, 1], etc.). The traversal would look something like this:

```
 1 13 |  3 15 |  5
 7 17 |  9 18 | 11
------+-------+---
 2 14 |  4 16 |  6
 8 19 | 10 20 | 12
```

Any other traversal ideas are welcomed.

Ideally, this algorithm would translate to a math formula to calculate the row & column based on the linear index, possibly with a few conditions (IF statements) to compensate for missing values, etc.

答:
Put all integers from 0 to NxM-1 into an array, shuffle that array randomly and pick the results one after another (mapping to row/column could be anything trivial like row=idx mod M , col=idx/M).

A good shuffle algorithm is Fisher-Yates shuffling, see here.


答:
There is not enough information to answer this question.  It depends on what getFooList actually does, and how it does it.

Here is an obvious example of a method which should support an additional parameter, used or not.

```<code>void CapitalizeSubstring (String capitalize_me, int start_index);
</code>```

Implementing a method that operates on a collection where you can specify the start but not the end of the collection is often silly.

You really have to look at the problem itself and ask whether the parameter is nonsensical in the context of the whole interface, and really how much burden the additional parameter imposes.

Body:
There is not enough information to answer this question.  It depends on what getFooList actually does, and how it does it.

Here is an obvious example of a method which should support an additional parameter, used or not.

void CapitalizeSubstring (String capitalize_me, int start_index);

Implementing a method that operates on a collection where you can specify the start but not the end of the collection is often silly.

You really have to look at the problem itself and ask whether the parameter is nonsensical in the context of the whole interface, and really how much burden the additional parameter imposes.


问:
Is SourceSafe really safe?
Having spent all morning trying to check something in - I now realise I've lost a couple of days worth of work.

Its happened before - and is apparently common occurrence with SourceSafe.  Can SourceSafe be used successfully, without problems, and if so, how?

答:
My views on VSS? Used it for a long time regularly (still used ocasionally for older components) but it's too XX century for our team:

Very unreliable

Not usable branches

Very poor versioning support, you have labels but (just like branches) not really usable

I'm with all of the above: choose one of the waaaaay better open-source alternatives (even old CVS) or, if your company has some kind of MSDN subscription, TFS.

Title: Is SourceSafe really safe?

ContentLicense: CC BY-SA 2.5


答:
Adding an unused parameter is confusing. People might call that method assuming this feature will work.

I wouldn't add it. It is trivial to later add it using a refactoring and mechanically fixing up the call sites. In a statically typed language this is easy to do. Not necessary to eagerly add it.

If there is a reason to have that parameter you can prevent the confusion: Add an assert in the implementation of that interface to enforce that this parameter be passed as the default value. If someone accidentally uses that parameter at least he will immediately notice during testing that this feature is not implemented. This takes away the risk of slipping a bug into production.


问:
Why not apply Interface Segregation Principle to "extreme"
Providing that clients would typically consume just one method, though methods would be conceptually related, why not always apply the Interface Segregation Principle to the extreme and have [many] single-method interfaces? Is there an objective rule against this? Not something like "oh it feels wrong" or "but you will have so many types, it's hard to read and manage" but rather something logical and clear. (Still want to name contracts clearly, so functions are not a good fit?).

Example:

```<code>IGeometryManager
{
   Shape CreateTriangle();
   Shape CreateCircle();
   Shape CreateSquare();
   Shape CreateEllipse();
   Shape CreateCurve();
   Shape CreateLine();
   void RemoveAll();
}
</code>```

Result:

```<code>ITriangleCreator
{
   Shape CreateTriangle();
}

ICircleCreator
{
   Shape CreateCircle();
}

ISquareCreator
{
   Shape CreateSquare();
}

IEllipseCreator
{
   Shape CreateEllipse();
}

ICurveCreator
{
   Shape CreateCurve();
}

ILineCreator
{
   Shape CreateLine();
}

IShapeRemover
{
   void RemoveAll();
}
</code>```

This is a relevant blog post, but I am not 100% persuaded by the authors logic: http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional

答:
There is someone who has developed this principle to the extreme, and further: the german software Engineer Ralf Westphal made a complete programming model from it and called it "Event Based Components", together with a design method, called Flow Design.  Actually, he does not use the "interface form", only Func or Action contracts, and he has got a lot of very good arguments why this is probably the better way to go.

He has published most articles about it in german, but here is an article in english about his approach, not by himself. Last year he published a (cheap) book about the topic.

ContentLicense: CC BY-SA 4.0


问:
How can a true Vector be implemented in Haskell?
How could a true Vector type be implemented in Haskell? In order for something to be a Vector, it has to be stored sequentially in memory, with O(1) random access. But Haskell hides its memory management, and its datatypes describe trees! So how could you express that kind of requirement?

答:
You should look at Data.Vector.Unboxed and Data.Vector.Mutable in the vector package:

https://hackage.haskell.org/package/vector


问:
Classic inheritance problem?
I keep seeing the following pattern when people learn about OOP:

Problem: How do I put objects of different but related types into a container?

Solution: Inherit from a common base class.

New problem: I have a bunch of base class objects, how do I get the real type?

Solution: ???

The classic inheritance example is to make a graphics program that deals with geometric objects. We have Circles, Ellipses and Triangles. All these objects have a common base Drawable.

In C++ this might look something like this:

```<code>struct Drawable{
    virtual ~Drawable(){}
    virtual void draw() const = 0;
};

struct Triangle : Drawable{
    Point p1, p2, p3;
    void draw() const override;
    void stretch(double xfactor, double yfactor);
    std::touple<double, double, double> getAngles() const;
    //...
};

struct Circle : Drawable{
    double radius;
    void draw() const override;
    //...
};

struct Ellipse : Drawable{
    double radius;
    void draw() const override;
    //...
};

std::vector<Drawable *> drawables = {new Circle, new Triangle, new Ellipse};
for (const auto &d : drawables)
    d->draw();
</code>```

So far so good. Now I want to increase the radius of my Circles and Ellipses. As far as I know there are 4 ways to do that:

1: Put everything into the base class. The base class gets the virtual functions getAngles, getRadius, stretch and getEccentricity. There is a default implementation for each so that for example getRadius returns some dummy value when you are dealing with a Triangle. After this is done you can easily iterate over the Drawables and increase their radius. This makes the base class ridiculously huge and working on a vector<Drawable *> becomes inefficient because the functions do nothing for most elements.

2: Use dynamic_cast hacks.

```<code>for (const auto &d : drawables){
    if (dynamic_cast<Circle *>(d))
        ((Circle *)d)->radius++;
    else if (dynamic_cast<Ellipse *>(d))
        ((Ellipse *)d)->radius++;
}
</code>```

Unfortunately you need to repeat this ugly syntax every time you need to do something like this. You cannot put it in a function or macro. Every time a new Drawable is added you have to go through the whole code base and add it where appropriate. Also the if/else-chain is fairly inefficient.

3: Add a Tag as the first member variable and cast accordingly.

```<code>for (const auto &d : drawables){
    switch(d->tag){
        case Tag::Circle:
            ((Circle *)d)->radius++;
            break;
        case Tag::Ellipse:
            ((Ellipse *)d)->radius++;
            break;
    }
}
</code>```

Slightly more efficient due to a switch instead of an if/else-chain, but there is already a kind of tag that shows the dynamic type, so the tag is redundant. Also it has the same problem as 2: since you need to change the whole code base whenever a new Drawable comes along.

4: Just keep the objects in separate containers.

```<code>vector<Circle> circles;
vector<Triangle> triangles;
vector<Ellipse> ellipses;
for (auto &c : circles)
    c.radius++;
for (auto &e : ellipses)
    e.radius++;
</code>```

This is very efficient memory layout wise and you only iterate over objects that matter. It is my favorite, but unfortunately it breaks the first solution in that you do not keep differently typed objects in a single container.

I tried to solve the problem by creating a variadic template that internally has a vector per type and forwards insertions to the right container. Ideally it would completely hide the fact that there are different containers under the hood. Usage would look something like this:

```<code>MultiVector<Triangle, Circle, Ellipse> mv;
mv.push_back(Triangle());
mv.push_back(Circle());
mv.push_back(Ellipse());
for (auto &d : mv.get<Circle, Ellipse>())
    d.radius++;
</code>```

The solution is not perfect, for example different types do not keep their order and implementing the iteration is tricky.

I presented this problem and solution attempt to my (university) research group and got the reactions "If you design your classes right this is not a problem" and "The proposed solution is a very specific tool to solve a very specific problem and it is questionable at best to add even more complexity to c++ for such a minor detail". In my opinion this is a very basic problem that needs fixing and the usual solution of better class design only tries to find the least evil of the 4 workarounds in the specific case without actually solving the problem. The problem comes up almost every time inheritance is used.

So finally here is the question: Did you run into this problem too / is this a real problem? Do you know of another workaround/solution? Do other languages deal better with the problem? I want to simulate a poll using 2 comments below so feel free to upvote either "I never had this problem / The problem is easily solved." or "I also had this problem and never solved it to my satisfaction."

Edit: To prevent a close due to primarily opinion based / discussion: I want a clear answer that solves the problem or some resource that says that there is none.

Edit: Related: Do I really have a car in my garage?

答:
This is a classic OOP issue, not that it signals that anything is wrong with the object oriented way of thinking, but it does require one to carefully consider the design.

When you wish to iterate over a container of objects, and alter some property that only a part of the objects have, and more importantly: only makes sense for a part of the objects, it is in my opinion the design that is the problem. The question here is, why do you want to alter some class specific property in a generic list? I am sure it make good sense in your situation, but think about it for a while.

You have a list of figures, this can be squares, rectangles, triangles, circles, polygons, etc. And now you wish to perform some action on them, which is fine, if they all support the action. But it does not make sense to alter a property on an object that would clearly not support it. It is counter-intuitive to iterate a list of figures, setting the radius, it is not however counter-intuitive to iterate a list of circles, setting the radius.

That does not mean, that some complicated, or let's just say smart design choice, can enable you to achieve this, but it goes against the concept of object orientation, by somehow trying to circumvent the encapsulation. I would argue, that this goes against the idea of polymorphism.

How to do it instead however is something different, which I am afraid I cannot produce an answer for at this moment. I do believe however, that you should do your utmost to try to avoid putting yourself in that situation.

One possible alternative you could look into is using a visitor pattern, where you have a visitor that accepts an object type that allows changing the radius. For instance:

```<code>class Visitor {
public:
  void Visit(Circle& circle) { /* Do something circle specific */ )
  void Visit(Square& square) { /* Do something square specific */ )
  // ...
};
</code>```

Title: Classic inheritance problem?

Body:
This is a classic OOP issue, not that it signals that anything is wrong with the object oriented way of thinking, but it does require one to carefully consider the design.

When you wish to iterate over a container of objects, and alter some property that only a part of the objects have, and more importantly: only makes sense for a part of the objects, it is in my opinion the design that is the problem. The question here is, why do you want to alter some class specific property in a generic list? I am sure it make good sense in your situation, but think about it for a while.

You have a list of figures, this can be squares, rectangles, triangles, circles, polygons, etc. And now you wish to perform some action on them, which is fine, if they all support the action. But it does not make sense to alter a property on an object that would clearly not support it. It is counter-intuitive to iterate a list of figures, setting the radius, it is not however counter-intuitive to iterate a list of circles, setting the radius.

That does not mean, that some complicated, or let's just say smart design choice, can enable you to achieve this, but it goes against the concept of object orientation, by somehow trying to circumvent the encapsulation. I would argue, that this goes against the idea of polymorphism.

How to do it instead however is something different, which I am afraid I cannot produce an answer for at this moment. I do believe however, that you should do your utmost to try to avoid putting yourself in that situation.

One possible alternative you could look into is using a visitor pattern, where you have a visitor that accepts an object type that allows changing the radius. For instance:

class Visitor {
public:
  void Visit(Circle& circle) { /* Do something circle specific */ )
  void Visit(Square& square) { /* Do something square specific */ )
  // ...
};


问:
Is Haskell appropriate for Signal Processing, Communication Systems and Information Theory?
I have been working on Software-Defined Radio projects for almost a year. This is an area which requires lots of signal processing (digital filters and FFTs), communication theory (modulation, equalization and synchronization) and information theory (specifically, coding theory, as Huffman, Linear and Convolutional codes). I program mostly in Matlab (for simulations) and C++ and Python (for practical applications using GNURadio and the USRP).

As you can see, those areas require lots of mathematical concepts. As I've been studying Haskell, I see that it is a good programming language for applications that involve heavy math.It seemed a good idea to program in Haskell for problems in the area I have been working on.

On the other hand, there doesn't seem to be a lot of people doing this. There seems to be a Haskell DSP library, but there aren't many projects using it available on the web. I've also found a thesis where Haskell was used to implement a Viterbi coder/decoder and it seems quite an elegant solution.

But it seems to me that people in the communication industry and research still don't use a lot of Haskell in their codes. Maybe this coulde be because many of them still haven't heard about Haskell.

What would be upsides and downsides of applying Haskell to those kind of problems? What will be key benefits of doing SDR in Haskell? What about Haskell would make it a bad choice for SDR? Should I expect severe pain points using Haskell for SDR (what are they?).

答:
I won't be able to provide answers to everything in your question, but I'll give ya what I know.

Good points

Flexibility of the language

Haskell should be a good language for writing code for the SDR domain:

Besides having good support for Embedded Domain-Specific Languages (EDSLs), Haskell code is highly composable, which will make it easy to work with signal processing concepts at a high abstraction level.

A library such as Pipes or Conduit will make it simple/easy to create filters (as functions) and chain them together to form processing pipelines. Arrowized Functional Reactive Programming (AFRP) might be another means to this end. (It uses some crazy circular programming wizardry under the hood.)

Libraries and external code

Haskell has what I've heard is a very good Foreign Function Interface (FFI) which lets it interface with C code, so you should have access to lots of libraries for doing signal processing through this. (I've not used the FFI directly myself, but I've used libraries which have.)

Some libraries pertinent to signal processing already have Haskell wrappers: the HMatrix library (warning: slow-loading PDF) is a wrapper around the LAPACK, BLAS, and GSL libraries, the first two of which I believe Matlab uses under the hood. The syntax of the Haskell code in this library seems like it should be easy to pick up for someone familiar with Matlab (I did a lot of Matlab back in school; I've only ever looked at HMatrix, not used it, but it looks niiiice).

Purely Functional

Haskell is purely functional which makes testing and verifying code easier than with an imperative language or one which supports mutability.

Bad points

Purely Functional

Haskell is purely functional, which means mutability can be tricky and it takes a different way of thinking to get things done. This shouldn't be too big of a problem if you go with a pipeline style architecture using one of the libraries I mentioned above.

Laziness

Haskell is a lazy language, which means that a value isn't computed until you try to use it*. If you're going to need a value right-away and it hasn't been computed yet, this can screw things up.

*This is probably a gross oversimplification.

Garbage collection

As with any language using garbage collection, there is a possibility it might kick in at the wrong time.

Why isn't it in use?

I think you may be correct in that people simply aren't aware of it in this field. Also, Haskell has a fairly steep learning curve, so people probably just stick with what they know.


问:
Does the usage of LINQ and Lambda Expressions lead to less readable code?
I'm having a discussion with a co-worker on Linq, I'll copy here:

Co-Worker: Lets be honest here. Linq
syntax sucks. It's confusing and
non-intuitive.

Me: oh come on, more
confusing than T-SQL?

Co-Worker: uh,
yes.

Me: it has the same basic
parts, select, where, and from

Co-Worker: Linq, to me, is a
bastardization of relational + OO.
Co-Worker: Don't get me wrong - it's
incredibly powerful, but they
repurposed SQL to use agains object
collections.

I'm of the opinion that using Linq + Lamda's is very powerful (he agrees), and also makes code easier to read (he disagrees on that point):

pickFiles = from f in pickFolder.GetFiles("*.txt")
where ValidAuditFileName.IsMatch(f.Name)
select f;
```
<p>or</p>
<pre class="lang-cs prettyprint-override"><code>var existing = from s in ActiveRecordLinq.AsQueryable<ScannedEntity>()
where s.FileName == f.FullName && s.DocumentType != "Unknown"
select s;
</code>```

or (VB code here)

   Dim notVerified = From image In images.AsParallel
     Group Join verifyFile In verifyFolder.GetFiles("*.vfy").AsParallel.Where(
      Function(v) v.Length > 0
      ).AsParallel
   On image.Name.Replace(image.Extension, ".vfy") Equals verifyFile.Name
     Into verifyList = Group
    From verify In verifyList.DefaultIfEmpty
    Where verify Is Nothing
    Select verify
```

To me this is clean and easy (at least easier than the alternatives) to read, what are your opinions on it?

答: I find LINQ syntax intuitive and easy to read, especially since they put the FROM at the start where it belongs instead of in the middle like in SQL.  But IMO lambdas are confusing and make the code harder to read.</p>


答:
```<code>Problem: How do I put objects of different but related types into a container?

Solution: Inherit from a common base class.
</code>```

This is the problem. If your design called for separate types, you shouldn't have to merge them for the sake of putting them into a container. You chose an example where no one will look at you funny if you merge them all under a common base class, but this solution clearly doesn't work when the types have less in common, or are primitive/scalar types, or are third party types you don't control.

What you want is a tagged union. C/C++ doesn't have these, but it does have untagged unions which you can tag yourself:

```<code>enum ShapeType { TRIANGLE, CIRCLE, ELLIPSE };

struct ShapeUnion {
    ShapeType type;
    union {
       Triangle triangle;
       Circle circle;
       Ellipse ellipse;
    } data;
};
</code>```

By checking the enum you can determine which member of the union to access:

```<code>std::vector<ShapeUnion> shapes = getShapes();
for (auto& shape: shapes) {
    switch (shape.type) {
        case TRIANGLE: foo(shape.data.triangle); break;
        case CIRCLE: bar(shape.data.circle); break;
        case ELLIPSE: baz(shape.data.ellipse); break;
        default: // raise some sort of error
    }
}
</code>```

I'm sure you can find templates for this if you google a bit.

Disclaimer: I don't write much C/C++, the above code may contain syntax errors.

Title: Classic inheritance problem?

Body:
I keep seeing the following pattern when people learn about OOP:

Problem: How do I put objects of different but related types into a container?

Solution: Inherit from a common base class.

New problem: I have a bunch of base class objects, how do I get the real type?

Solution: ???

The classic inheritance example is to make a graphics program that deals with geometric objects. We have Circles, Ellipses and Triangles. All these objects have a common base Drawable.

In C++ this might look something like this:

```<code>struct Drawable{
    virtual ~Drawable(){}
    virtual void draw() const = 0;
};

struct Triangle : Drawable{
    Point p1, p2, p3;
    void draw() const override;
    void stretch(double xfactor, double yfactor);
    std::touple<double, double, double> getAngles() const;
    //...
};

struct Circle : Drawable{
    double radius;
    void draw() const override;
    //...
};

struct Ellipse : Drawable{
    double radius;
    void draw() const override;
    //...
};

std::vector<Drawable *> drawables = {new Circle, new Triangle, new Ellipse};
for (const auto &d : drawables)
    d->draw();
</code>```

So far so good. Now I want to increase the radius of my Circles and Ellipses. As far as I know there are 4 ways to do that:

1: Put everything into the base class. The base class gets the virtual functions getAngles, getRadius, stretch and getEccentricity. There is a default implementation for each so that for example getRadius returns some dummy value when you are dealing with a Triangle. After this is done you can easily iterate over the Drawables and increase their radius. This makes the base class ridiculously huge and working on a vector<Drawable *> becomes inefficient because the functions do nothing for most elements.

2: Use dynamic_cast hacks.

```<code>for (const auto &d : drawables){
    if (dynamic_cast<Circle *>(d))
        ((Circle *)d)->radius++;
    else if (dynamic_cast<Ellipse *>(d))
        ((Ellipse *)d)->radius++;
}
</code>```

Unfortunately you need to repeat this ugly syntax every time you need to do something like this. You cannot put it in a function or macro. Every time a new Drawable is added you have to go through the whole code base and add it where appropriate. Also the if/else-chain is fairly inefficient.

3: Add a Tag as the first member variable and cast accordingly.

```<code>for (const auto &d : drawables){
    switch(d->tag){
        case Tag::Circle:
            ((Circle *)d)->radius++;
            break;
        case Tag::Ellipse:
            ((Ellipse *)d)->radius++;
            break;
    }
}
</code>```

Slightly more efficient due to a switch instead of an if/else-chain, but there is already a kind of tag that shows the dynamic type, so the tag is redundant. Also it has the same problem as 2: since you need to change the whole code base whenever a new Drawable comes along.

4: Just keep the objects in separate containers.

```<code>vector<Circle> circles;
vector<Triangle> triangles;
vector<Ellipse> ellipses;
for (auto &c : circles)
    c.radius++;
for (auto &e : ellipses)
    e.radius++;
</code>```

This is very efficient memory layout wise and you only iterate over objects that matter. It is my favorite, but unfortunately it breaks the first solution in that you do not keep differently typed objects in a single container.

I tried to solve the problem by creating a variadic template that internally has a vector per type and forwards insertions to the right container. Ideally it would completely hide the fact that there are different containers under the hood. Usage would look something like this:

```<code>MultiVector<Triangle, Circle, Ellipse> mv;
mv.push_back(Triangle());
mv.push_back(Circle());
mv.push_back(Ellipse());
for (auto &d : mv.get<Circle, Ellipse>())
    d.radius++;
</code>```

The solution is not perfect, for example different types do not keep their order and implementing the iteration is tricky.

I presented this problem and solution attempt to my (university) research group and got the reactions "If you design your classes right this is not a problem" and "The proposed solution is a very specific tool to solve a very specific problem and it is questionable at best to add even more complexity to c++ for such a minor detail". In my opinion this is a very basic problem that needs fixing and the usual solution of better class design only tries to find the least evil of the 4 workarounds in the specific case without actually solving the problem. The problem comes up almost every time inheritance is used.

So finally here is the question: Did you run into this problem too / is this a real problem? Do you know of another workaround/solution? Do other languages deal better with the problem? I want to simulate a poll using 2 comments below so feel free to upvote either "I never had this problem / The problem is easily solved." or "I also had this problem and never solved it to my satisfaction."

Edit: To prevent a close due to primarily opinion based / discussion: I want a clear answer that solves the problem or some resource that says that there is none.

Edit: Related: Do I really have a car in my garage?

Body:
Problem: How do I put objects of different but related types into a container?

Solution: Inherit from a common base class.

This is the problem. If your design called for separate types, you shouldn't have to merge them for the sake of putting them into a container. You chose an example where no one will look at you funny if you merge them all under a common base class, but this solution clearly doesn't work when the types have less in common, or are primitive/scalar types, or are third party types you don't control.

What you want is a tagged union. C/C++ doesn't have these, but it does have untagged unions which you can tag yourself:

enum ShapeType { TRIANGLE, CIRCLE, ELLIPSE };

struct ShapeUnion {
    ShapeType type;
    union {
       Triangle triangle;
       Circle circle;
       Ellipse ellipse;
    } data;
};

By checking the enum you can determine which member of the union to access:

std::vector<ShapeUnion> shapes = getShapes();
for (auto& shape: shapes) {
    switch (shape.type) {
        case TRIANGLE: foo(shape.data.triangle); break;
        case CIRCLE: bar(shape.data.circle); break;
        case ELLIPSE: baz(shape.data.ellipse); break;
        default: // raise some sort of error
    }
}

I'm sure you can find templates for this if you google a bit.

Disclaimer: I don't write much C/C++, the above code may contain syntax errors.


答:
So here's the issue: what's classical inheritance really all about? Taxonomy! Strict hierarchies and the like. Hierarchies work based on commonality of the types. So now you're trying to say, "I want to group unlike things together". Ok, you can do that. But since they're not the same type, a problem solving pattern based on similarity isn't likely to work well for acting on them as a group ... unless you find the way in which they are similar. If they really are similar, you can act on them as a group in some abstract way by making a base class and you shouldn't need to switch on type. If they're not similar at all, you can't act on them without switching on the type. And really, let's face it: polymorphism really is doing this by switching which implementation is called under the hood, so in some odd way it too is like a switch statement - just faster and more elegant.

So when you think about it this way, you've got to put the switch either into the class itself (classical inheritance, probably with some strange "DoStuff()" or "Process()" method) or into the the thing acting on the class (visitor pattern or switch on types) or segregate the lists (solution #4). The advantage of the visitor/switch on type is that it doesn't muddy up your base class and is therefore nicer for modular code.

Now OOP isn't the only paradigm in town. Game designers often have to think about objects that don't form a strict hierarchy, but rather have certain "attributes". You might find component design or related variants interesting if you run into this type of problem often.

Title: Classic inheritance problem?


答:
You asked:

Did you run into this problem too / is this a real problem? Do you know of another workaround/solution?

My answer to that is a big YES. I deal with this a lot at my work.

You said,

Now I want to increase the radius of my Circles and Ellipses.

The key to your solution lines in delving into the details of that requirement. There is no "I" in code. You have to identify which parts of your code needs to perform that operation. That section of your code must know about Circles and Ellipses. If that section of the code knows about Circles and Ellipses, they can take a base class pointer or reference and perform a dynamic_cast. If the dynamic_cast succeeds, they can call the member functions directly. If the dynamic_cast does not succeed, they can ignore that object, throw an exception, or deal with it some other way.

A generic approach

We have dealt with generic properties using string based keys and generic values. For example, a generic property handler associated with Circles and Ellipses would register itself indicating that it knows how to deal with the "radius" properties of objects. A generic dispatch mechanism would call that property handler when it needs to set the "radius" of a Drawable.

In pseudo code, you would have:

```<code>void setProperty(Drawable& dr, std::string const& key, std::string const& value)
{
    PropertyHandler* handler = getPropertyHandler(key);
    if ( handler != NULL )
    {
       handler.setProperty(dr, key, value);
    }
}
</code>```

Title: Classic inheritance problem?

Body:
You asked:

Did you run into this problem too / is this a real problem? Do you know of another workaround/solution?

My answer to that is a big YES. I deal with this a lot at my work.

You said,

Now I want to increase the radius of my Circles and Ellipses.

The key to your solution lines in delving into the details of that requirement. There is no "I" in code. You have to identify which parts of your code needs to perform that operation. That section of your code must know about Circles and Ellipses. If that section of the code knows about Circles and Ellipses, they can take a base class pointer or reference and perform a dynamic_cast. If the dynamic_cast succeeds, they can call the member functions directly. If the dynamic_cast does not succeed, they can ignore that object, throw an exception, or deal with it some other way.

A generic approach

We have dealt with generic properties using string based keys and generic values. For example, a generic property handler associated with Circles and Ellipses would register itself indicating that it knows how to deal with the "radius" properties of objects. A generic dispatch mechanism would call that property handler when it needs to set the "radius" of a Drawable.

In pseudo code, you would have:

void setProperty(Drawable& dr, std::string const& key, std::string const& value)
{
    PropertyHandler* handler = getPropertyHandler(key);
    if ( handler != NULL )
    {
       handler.setProperty(dr, key, value);
    }
}


问:
Is it a good idea to do contract work for a former full time employer?
Assuming:

The employee and company are parting on good terms

The new company is OK with a little contract work as long as it doesn't distract from the new job

The former company wants the help and the employee is willing to work a few hours a week

Is it a good idea to do contract work for a former full time employer?

Has anyone ever done this?  How did it work out for you?  I can see some possible pitfalls, so I wonder how good an idea it really is.  What difficulties do you encounter doing development work outside the office and on a different schedule from the rest of the programming staff and how can they be overcome?

If I  do go forward, what would be a fair amount to request as compared to current salary?

答: Make sure the IP section in your employment contract and your freelance contract are compatible with each other.  If not, try to get them changed.  If your employment contract says your current company owns all the work you do, that could start an ugly legal fight later.  Example: one of the companies gets acquired, and the acquirer demands said company own all the IP rights, but the other company refuses to sign any legal document.  For best results, get an attorney to review both contracts.</p>


问:
What does mathematics have to do with programming?
I just started a diploma in software development. Right now we're starting out with basic Java and such (so right from the bottom you might say) - which is fine, I have no programming experience apart from knowing how to do "Hello World" in Java.

I keep hearing that mathematics is pertinent to coding, but how is it so? What general examples would show how mathematics and programming go together, or are reliant on one another?

I apologize of my question is vague, I'm barely starting to get a rough idea of the kind of world I'm stepping into as a code monkey student...

答:
The actions of doing Mathematics and 99% of Programming have very little in common.  Math is not required to be a great programmer.  I've taken several college level courses in math, including but not limited to Calculus I,II,III elements of linear algebra, and several others.

I've been a software engineer for over 10 years and only rarely needed to use anything more than basic mathematics.  There are some exceptions where mathematics is needed: like graphics and other areas.  But 99% of the programming and software engineering doesn't require Math.  It requires logical thinking, algorithms, OOP, functions, decomposing problems, etc.