问:
Fill widget with data retrieved from internet
I want to retrieve data from internet and show them into a widget.

In particular, I've a widget with a QComboBox containing some service from which I can retrieve a list of exchange markets.

When I select one item, I want to show related markets in a QTextEdit on the same widget.

In my mind I think to do following steps:

Send the request signal when item is selected

Start retrieving of data from internet with QNetworkManager

At the same time showing a modal waiting widget (with a progress bar or similar)

When data is retrieved and parsed, emit a signal with data received from both waiting widget (that will be closed) and to original widget which will be updated.

If some error occurs (no internet connection, timeout etc) send another signal with the error code, received from the waiting widget that will shown the error message and then closed. No changes in original widget.

It's a good way to update a widget with data received from internet (or another slow source)? Or is there a better way, or a design pattern to follow in such cases?

答:
When you say QNetworkManager, are you referring to QNetworkAccessManager?

In my opinion, it's the best solution in Qt and I do think is the right one.

The steps you mentioned sound good also.


问:
Forcing Cache Refresh

I'm updating an existing tomcat web application to read certain resources from a REST API. Currently the application reads them from flat files. Since the application is very critical, I added a caching layer so that the objects returned by REST API are always available.

In the service layer of API client, if the request item is not found in the Cache, the request will be sent to the actual API, the response is put in MapDB cache and returned to caller. The startup listener calls a bunch of APIs with different parameters so that all data is now in MapDB cache. I do not set a expiration on the items in cache because I want them to always available unless I refresh on demand.

The problem is Web App and API client are different projects. Since API client decides to read from Cache or API, I'm not able to force refresh cache value from the application.

Should I add another parameter to function calls I make to API client or

```<code>Object obj = ServiceFactory.getLanguageService()
                    .getLanguagesFromApi(env.getName(),
                            env.getEnvironmentType(),
                            env.getPhase().toString(), null, true);
</code>```

The last "true" parameter indicates forcing cache refresh.

Should I get the existing value in cache to a temporary variable, delete the entry, make API call, if no value is returned because of some error, put the entry back into the cache.

```<code>        String key = ClientUtils.concatenateList(
                Arrays.asList(ClientConstants.RESOURCE_LANGUAGE,
                        env.getName(), env.getEnvironmentType(),
                        env.getPhase(), null),
                ClientConstants.CACHE_KEY_SEPERATOR,
                ClientConstants.NULL_STRING);

        Object cachedElement = ClientCache.getCache().get(key);
        if (cachedElement != null) {
            ClientCache.getCache().delete(key);
        }

        Object obj = ServiceFactory.getLanguageService()
                .getLanguagesFromApi(env.getName(),
                        env.getEnvironmentType(),
                        env.getPhase().toString(), null);

        if (obj == null) {
            ClientCache.getCache().put(key, cachedElement);
        }
</code>```

What is the cleaner way to do this ? I feel adding parameters about caching to function makes it clumsy and add dependencies - like getUsers(String country, boolean forceAPIrequest). But deleting and adding same entries may also waste resources and heap space, causing GC over time. Also, App will directly access Client Cache to do these operations.

All this is based on strong assumption that our REST API is unreliable. Web App should not have any down time.

答:
If I understand correctly, caching is in place mainly for realiability in case of unavailability of REST service, not for performance.

In that case, you could call REST service every time you receive request from the client, if you get a response (REST service is working) you update the MapDB cache and return the response to API client. If REST service is down and you don't get the response, simply return cached value from MapDB.

This way your clients get always as up-to-date possible version as possible while keeping the reliability requirement.

You could include a flag in the response to your clients indicating whether the response is from cache or up-to-date. This might be useful for clients which absolutely require up-to-date response to the point that it is preferable to fail than to work with old data.

ContentLicense: CC BY-SA 3.0

Title: Forcing Cache Refresh


问:
Super user powers in development environment?
Is it too much to ask for when I ask the IT department to give my development team an environment where we can use whatever software that we can download without having to have security check those tools?

Of course, the software can be checked by security before deploying to Test, and the development environment can be on a VLAN that is not accessible from outside.  This would greatly aid us by allowing us to use whatever open-source testing tools that we want.

I'm asking because we have such tight restrictions on the software approval process, and I hear of other teams that have an environment where they can configure their local server however they want and they can use whatever tools they want.  What's the norm out there?

Thank you for any comments!

答:
Is it too much to ask ... an environment where we can use whatever software that we can download without having to have security check those tools?
  Short answer: Yes.

If you're "doing" Scrum properly, then you'll be producing Production-ready code every a couple of sprints; four weeks may not be anywhere near long enough for this downloaded Thing-a-ma-jig to be checked out - by whoever needs to do that checking.  If that includes your company's legal team, expect a long lead time.

Also, I would say that "security checking" is only part of your problem.

In my experience, "pure Development" teams all too often forget that whatever they develop has to be supported, so your Support team(s) will have to get up to speed with this latest and greatest piece of whatever-it-is, before they can commit to taking calls about it from angry customers, if and when it stops working.

If you deliver Sprint 11 using utility #1 and then, in Sprint 13, decide to shift to utility #2 and then, again, in Sprint 17 to utility #3 then you, as a Development team, can forget about utilities #1 and #2 (you're never going to need them again) but your Support Team(s) may be stuck supporting all three.

Not a good way to make Friends and Influence people, I would suggest.

OwnerDisplayName: red tiger

ContentLicense: CC BY-SA 2.5


问:
Deployment Environment Responsibility
This might be not technical but rather process driven query. Help me redirect to right forum if this is not the place to ask such question.

Typically in a project, we have a deployment environment where development team deploy the code for testing purpose. Testing team executes test cases on the environment.

But I have seen projects where there are multiple environments for different teams to test on, and when I get to understand that what's the point? I do not see any reason than to have multiple environments.

Two environments:

1. Lower Environment-  Developers can use this environment to test their code( this environment will be an exact replica of higher environment where Internal and External testing will happen). We use SVN and checkin the code.

2. Higher Environment - where multiple testing team can test which from my experience seems stable env. to test on.

But we have lot of environments....and time to time support has to give on different environment.

But I see multiple environment where testing happens with no apparent concrete reason. My question is who's responsibility to support multiple environments? I find it difficult for development team to work on supporting multiple environments apart from regular dev activities, Unit test case preparation, get clarification from the design or business on User story.

Any suggestions would be highly appreciated.

答:
In modern development, team should be responsible for project analysis, design (architects may align flawed design), development, unit testing, automated QA/UAT/PERF testing, deploying it into all envs, operating and monitoring in production till the project is decommissioned from PROD or not used by customers.

Modern development practices involves automation of everything into single build, test, deploy pipeline.

The idea is to provide to the team platform with self-services, so that team can achieve all above tasks with smallest possible outside interaction. Any ticketing system is burden that should be changed to self-service.

So in such environment would have cross-functional team members (YES sometimes developers writing non-unit tests and be woken up in the night if the application is down). Idea is to have on team experts on each area of development process and mentor members of the team not familiar with certain skills. So you can end up that tester or operations engineer will be mentoring you.

You are lucky if you are already working in such company, but if it is not at least investing and trying to convert itself towards full automation Continouous Delivery/Deployment, it's time for you to change the company!

Title: Deployment Environment Responsibility


问:
Are clean coding rules less relevant for large open source projects?
I've been reading Robert Martin's book "Clean Code". One of his core tenants is to remove unnecessary comments and strive to create meaningful variable/method names that are self documenting.

Some of my colleagues disagree with this approach arguing that it is impractical for large software projects. They cite the example of jQuery's codebase which is littered with comments, unclear variable names like fn and sometimes even commented out code, e.g. jquery/deferred.js

Their conclusion is that open source code can't really follow clean coding principles because people want line by line explanations for why a particular approach was used and so liberal comments are a necessity. They also argue that the long descriptive method names advocated by Uncle Bob are harder to read than a short name with a descriptive function comment.

Do you think this conclusion is true? If not, do you have examples of vendor codebases that follow Clean Code principles faithfully?

Codebases I've examined

jQuery:

see above

Angular JS:

Example: Angular.js

- lots of comments that sometimes seem disconnected with context

- very long methods not following the extract method pattern

React JS

Example: ReactComponent.js

- Not much vertical spacing to separate code blocks

- relatively long methods not following extract method pattern

+ comments relatively rare and generally used to explain obtuse cases that would not be obvious

答:
... people want line by line explanations for why a particular approach was used ...

Can you can read and understand what the code does?  You don't need comments.

Do you understand why the code does what it does?  You don't need comments.

Otherwise, comments are probably a Good Idea.

Now: wind the clock forward "some time" (years?  months?  weeks, even?)

Can you still understand what the code does?  Why it does it?

This is where good commenting pays for itself.

You're not going to remember any given piece of code a year after you write it, but your comments should help you get "back into it" faster.


问:
What are the differences among the .NET certification exams?
I am a .NET developer using WPF and ASP.NET MVC and I was hoping to pass some kind of certification exam.

There seems to be four exams but I am unable to understand what the differences are even with Microsoft's definitions:

MCPD

MCAD

MCSD

MTA

How do they relate to each other? Is there a natural progression path through the certification exams? What version of .NET are they suited for?

答:
Difference between MCPD, MCAD, MCA/MCM

MCPD is thing that you should go for being a .Net Developer

Path is: MCP > MCTS > MCPD

There is no specific certification for Silverlight. you need to do certifications for WPF + WCF instead.

MCTS: .NET Framework 3.5 Windows Communication Foundation Applications Exam 70-536 and Exam 70-503

MCTS: .NET Framework 3.5 Windows Presentation Foundation Applications Exam 70-536 and Exam 70-502

MCTS is more focussed on development Technologies like Dot Net Framework 2.0, 3.5 and 4 and technologies like Desktop development, ADO.net, WPF, WCF etc. YOu should be following the path MCP > MCTS > MCPD

You will need to 70-536  .Net Framework 2.0 Application Development Foundation. This will make you an MCP. Then you can choose any MCTS Certification that may either relate to Web Development or Desktop Development, Distributed Application Development, Windows Development or more. Then after the completion of MCTS in one more (at least one) you will need to go for MCPD for that specific MCTS you have completed.

Windows technologies

Microsoft Visual Studio and Microsoft .NET Framework technologies

Microsoft SQL Server technologies

Microsoft Office System technologies (including Office SharePoint Server and Office Project Server)

Microsoft Exchange Server technology

Other technologies

MCPD Certifications are more closely related to software development using .Net Technologies.

MCPD on Microsoft Visual Studio 2010

MCPD on Microsoft Visual Studio 2008

MCPD on Microsoft Visual Studio 2005

MCPD on Microsoft SharePoint 2010

MCAD contain mostly retired exams. You may call these Legacy Certification program.You should not be going for it.

MCSD is a retired certifications program. You should not go for it.

There is no such thing as MTA I guess. You probably meant MCA (Microsoft Certified Architect). This program is currently limited to certification related to the following MS Solutions.
Microsoft currently offers three MCA certifications:

MCA: Microsoft Exchange Server

MCA: Microsoft SQL Server

MCA: Windows Server: Directory

Microsoft plans to extend the MCA certifications to include two other technologies:

MCA: Microsoft Office Communications Server

MCA: Microsoft Office SharePoint Server

Steps to Become MCA

MCM is Solution Specific. Not strictly related to coding or development from scratch. Its about being able to develop solutions out of Microsoft solutions like:

MCM: Microsoft Exchange Server 2010

MCM: Microsoft Lync Server 2010

MCM: Microsoft SharePoint Server 2010

MCM: Microsoft SQL Server 2008

MCM: Windows Server 2008 R2: Director

Preparations

Microsoft provides Self-Paced Training Kits for almost all of of its Exams.
Various third party sites also sell sample test papers. You may google them.

Mostly the exams are easy if you have experience of 2-3 years in development using .Net technologies. You may start here:

MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0 Foundation

Difficult Level between each

Not all of them are strictly related to one another except MCP, MTS, MCPD and MCM. They are not hard at all if you relevant experience. If you dont I suggest that you go through the relevant Self-Paced Training kit from Microsoft.

OwnerDisplayName: John Mitchel


问:
C# DbContext with nested classes containing the Repository methods
So I have done a lot of reading and it appears that, since DbContext already implements a repository and unit of work pattern combination, creating more abstraction classes would be redundant. However, I would still like to be able to encapsulate commonly-used queries for code reuse. I was thinking - perhaps I may be able to store a query-container class that uses the current instance of DbContext to make sure that queries don't cross transaction boundaries. Take for instance, this dummy code:

```<code>public partial class PersonEntities : DbContext
{
    public PersonEntities() : base("name=SomeConnectionString")
    {
        this.Configuration.ProxyCreationEnabled = false;
        this.CustomersQuery = new CustomerQueries(this);
    }

    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Employees> Employees { get; set; }

    public CustomerQueries CustomersQuery { get; }

    public class CustomerQueries
    {
        protected PersonEntities Database { get; private set; }

        internal CustomerQueries(PersonEntities db)
        {
            this.Database = db;
        }

        public IEnumerable<Customer> GetCustomersByName(string firstName, string lastName, bool ignoreCase = true)
        {
            /// method implementation
        }
    }
}
</code>```

You might use it like this (concrete classes and lack of factories for simplification):

```<code>        using (var context = new PersonEntities())
        {
            var query = context.CustomersQuery.GetCustomersByName("Alfred", "Morris", true);

            /// stuff

            await context.SaveChanges();
        }
</code>```

Pros:

Does not add additional abstraction

Queries can use multiple DbSets at once within the same transaction, unlike with many of the repository (especially generic repository) implementatinos I've seen.

Related queries are neatly contained in a single place with mostly only relevant methods (plus the common object methods like ToString), meanwhile DbSet class itself has tons of methods thanks to IEnumerable/IQueryable/etc extension methods and thus extending DbSet didn't seem like a good idea.

It also becomes possible to make some generic queries, such as:
GetPersonbyName<TPerson>(string firstName, stringLastName) where TPerson : Person, perhaps contained in a PersonsQuery class.

Cons

Adds additional functionality that could be considered bloating, potentially leading to a 'god class' - however, these queries are still tightly coupled to the DbSets and are still in sub-classes so I'm not sure if this is the case.

Perhaps others? I'm not really sure.

Are there any other drawbacks to using this style for code-reuse without redundant abstractions?

答:
For this sort of thing I like to use C# extension methods against IQueryable<>.  You would still have a class do define these but it wouldn't be nested in or referenced from your context.

Example:

```<code>public static class IQueryableOfCustomerExtensions
{
    public static IQuerable<Customer> GetByName(this IQueryable<Customer> customers, string firstName, string lastName, bool ignoreCase = true)
    {
        // Implementation
    }
}
</code>```

You could then call this like:

```<code>var customers = context.Customers.GetByName("Alfred", "Morris", true).ToList();
</code>```

Body:
For this sort of thing I like to use C# extension methods against IQueryable<>.  You would still have a class do define these but it wouldn't be nested in or referenced from your context.

Example:

public static class IQueryableOfCustomerExtensions
{
    public static IQuerable<Customer> GetByName(this IQueryable<Customer> customers, string firstName, string lastName, bool ignoreCase = true)
    {
        // Implementation
    }
}

You could then call this like:

var customers = context.Customers.GetByName("Alfred", "Morris", true).ToList();


答:
Just to be clear, Bob did not invent the concept of clean code. He just wrote a book with that title containing some very sound advice and some more dubious advice and opinions. I will bet all maintainers of large open source projects believe in clean code, but they do not necessarily adhere to all the principles in that specific book.

That said, I think you are misstating the opinion of Bob regarding comments. Bob advocates removing unnecessary comments. Unnecessary comments are comments which state what is already obvious from the code, like the classical:

```<code>// increment i by one
i++;
</code>```

Or comments that only compensate for bad variable/function naming or needlessly convoluted code.

But "line by line explanations for why a particular approach was used" is definitely not unnecessary, since code - however clean it is written - typically does not in itself explain why a certain approach is used.

Looking at the source for Angular.js for example, you find two kinds of comments.

1) API documentation comments like:

```<code>/**
 * @ngdoc function
 * @name angular.isObject
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
 * considered to be objects. Note that JavaScript arrays are objects.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is an `Object` but not `null`.
 */
</code>```

2) Inline explantation comments like:

```<code>// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
</code>```

Both kind of comments are absolutely an indication of clean, high quality code. The API documentation explains the workings of the library for the user, and the inline comments explain why the code is written as it is, i.e. it provides information which is not present in the code itself.

Title: Are clean coding rules less relevant for large open source projects?

Body:
I've been reading Robert Martin's book "Clean Code". One of his core tenants is to remove unnecessary comments and strive to create meaningful variable/method names that are self documenting.

Some of my colleagues disagree with this approach arguing that it is impractical for large software projects. They cite the example of jQuery's codebase which is littered with comments, unclear variable names like fn and sometimes even commented out code, e.g. jquery/deferred.js

Their conclusion is that open source code can't really follow clean coding principles because people want line by line explanations for why a particular approach was used and so liberal comments are a necessity. They also argue that the long descriptive method names advocated by Uncle Bob are harder to read than a short name with a descriptive function comment.

Do you think this conclusion is true? If not, do you have examples of vendor codebases that follow Clean Code principles faithfully?

Codebases I've examined

jQuery:

see above

Angular JS:

Example: Angular.js

- lots of comments that sometimes seem disconnected with context

- very long methods not following the extract method pattern

React JS

Example: ReactComponent.js

- Not much vertical spacing to separate code blocks

- relatively long methods not following extract method pattern

+ comments relatively rare and generally used to explain obtuse cases that would not be obvious

Body:
Just to be clear, Bob did not invent the concept of clean code. He just wrote a book with that title containing some very sound advice and some more dubious advice and opinions. I will bet all maintainers of large open source projects believe in clean code, but they do not necessarily adhere to all the principles in that specific book.

That said, I think you are misstating the opinion of Bob regarding comments. Bob advocates removing unnecessary comments. Unnecessary comments are comments which state what is already obvious from the code, like the classical:

// increment i by one
i++;

Or comments that only compensate for bad variable/function naming or needlessly convoluted code.

But "line by line explanations for why a particular approach was used" is definitely not unnecessary, since code - however clean it is written - typically does not in itself explain why a certain approach is used.

Looking at the source for Angular.js for example, you find two kinds of comments.

1) API documentation comments like:

/**
 * @ngdoc function
 * @name angular.isObject
 * @module ng
 * @kind function
 *
 * @description
 * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
 * considered to be objects. Note that JavaScript arrays are objects.
 *
 * @param {*} value Reference to check.
 * @returns {boolean} True if `value` is an `Object` but not `null`.
 */

2) Inline explantation comments like:

// Need to check if hasOwnProperty exists,
// as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function

Both kind of comments are absolutely an indication of clean, high quality code. The API documentation explains the workings of the library for the user, and the inline comments explain why the code is written as it is, i.e. it provides information which is not present in the code itself.


问:
Reducing the complexity of a class
I have looked at some answers and searched on Google, but I could not find anything helpful (i.e., that wouldn't have awkward side effects).

My problem, in abstract, is that I have an object and need to perform a long sequence of operations on it; I think of it as a sort of assembly line, like building a car.

I believe these objects would be called Method Objects.

So in this example at some point I would have a CarWithoutUpholstery on which I would then need to run installBackSeat, installFrontSeat, installWoodenInserts (the operations do not interfere with one another, and might even be done in parallel). These operations are performed by CarWithoutUpholstery.worker() and yield a new object which would be a CarWithUpholstery, on which I would then run maybe cleanInsides(), verifyNoUpholsteryDefects(), and so on.

The operations in a single phase are already independent, i.e., I am already grappling with a subset of them that may be executed in any order (front and rear seats may be installed in any order).

My logic currently uses Reflection for simplicity of implementation.

That is, once I have a CarWithoutUpholstery, the object inspects itself for methods called performSomething(). At that point it executes all these methods:

```<code>myObject.perform001SomeOperation();
myObject.perform002SomeOtherOperation();
...
</code>```

while checking errors and stuff. While order of operation is unimportant, I have assigned a lexicographic order in case I ever discover some order is important after all. This contradicts YAGNI, but it costed very little - a simple sort() - and it could save a massive method renaming (or introducing some other method of performing tests, e.g. an array of methods) down the line.

A different example

Let us say that instead of building a car I have to compile a Secret Police report on somebody, and submit it to my Evil Overlord. My final object will be a ReadyReport. To construct it I start by gathering basic information (name, surname, spouse...). This is my Phase A. Depending on whether there is a spouse or not, I may then have to proceed to phases B1 or B2, and gather sexuality data on one or two people. This is made of several different queries to different Evil Minions controlling night life, street cams, sex shop sales receipts and what not. And so on and so forth.

If the victim has no family, I will not even enter the GetInformationAboutFamily phase, but if I do, then it's irrelevant whether I first target the father or the mother or the siblings (if any). But I cannot do that if I haven't performed a FamilyStatusCheck, which therefore belongs to an earlier phase.

It all works wonderfully...

if I need some additional operation I only need to add a private method,

if the operation is common to several phases I can have it inherited from a superclass,

operations are simple and self-contained. No value from one operation is ever required by any of the others (operations that do are performed in a different phase),

objects down the line do not need to perform many tests since they could not even exist if their creator objects hadn't verified those conditions in the first place. I.e., when placing inserts in the dashboard, cleaning the dashboard and verifying the dashboard, I needn't verify that a dashboard is actually there.

it allows for easy testing. I can easily mock a partial object and run any method on it, and all operations are deterministic black boxes.

...but...

The problem arose when I added one last operation in one of my method objects, which caused the overall module to exceed a mandatory complexity index ("less than N private methods").

I have already taken the matter upstairs and suggested that in this case, the wealth of private methods is not a telltale of disaster. The complexity is there, but it's there because the operation is complex, and actually it's not all that complex - it's just long.

Using the Evil Overlord example, my problem is that the Evil Overlord (aka He Who Shall Not Be Denied) having requested all dietary information, my Dietary Minions telling me that I need to query restaurants, kitchenettes, street vendors, unlicensed street vendors, greenhouse owners etc., and the Evil (sub)Overlord - familiarly known as He Who Also Shall Not Be Denied - complaining that I'm performing too many queries in the GetDietaryInformation phase.

Note: I am aware that from several points of view this is not a problem at all (ignoring possible performance issues etc.). All that's happening is that a specific metric is unhappy, and there is justification for that.

What I think I could do

Apart from the first, all these options are doable and, I think, defensible.

I have verified that I can be sneaky and declare half my methods protected. But I'd be exploiting a weakness in the testing procedure, and apart from justifying myself when caught, I don't like this. Also, it's a stopgap measure. What if the number of required operations doubles? Unlikely, but what then?

I can split arbitrarily this phase into AnnealedObjectAlpha, AnnealedObjectBravo and AnnealedObjectCharlie, and have one third the operations being performed at each stage. I am under the impression that this actually adds complexity (N-1 more classes), with no benefit except for passing a test. I can of course hold that a CarWithFrontSeatsInstalled and a CarWithAllSeatsInstalled are logically successive stages. The risk of a Bravo method being later required by Alpha is small, and even smaller if I play it well. But still.

I can bunch different operations, remotely similar, in a single one. performAllSeatsInstallation(). This is only a stopgap measure and it does increase the complexity of the single operation. If I ever need to do operations A and B in a different order, and I have packed them inside E = (A+C) and F (B+D), I'll have to unbundle E and F and shuffle the code around.

I can use an array of lambda functions and neatly sidestep the check altogether, but I find that clunky. This is however the best alternative so far. It would get rid of reflection. The two problems I have is that I would probably be asked to rewrite all method objects, not only the hypothetic CarWithEngineInstalled, and while that would be very good job security, it really doesn't appeal all that much; and that the code coverage checker has issues with lambdas (which are solvable, but still).

So...

Which, you think, is my best option?

Is there a better way I haven't considered? (perhaps I'd better come clean and ask directly what is it?)

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed? For this last option I'd need references... I can't just wave my hand at the @PHB while murmuring These aren't the metrics you're looking for. No matter how much I'd like to be able to

答:
The long sequence of operations seems like it should be its own class, which then needs additional objects to perform its duties. It sounds like you are close to this solution. This long procedure can be broken down into multiple steps or phases. Each step or phase could be its own class that exposes a public method. You would want each phase to implement the same interface. Then your assembly line keeps track of a list of phases.

To build on your car assembly example, imagine the Car class:

public class Car
{
    public IChassis Chassis { get; private set; }
    public Dashboard { get; private set; }
    public IList<Seat> Seats { get; private set; }

    public Car()
    {
        Seats = new List<Seat>();
    }

    public void AddChassis(IChassis chassis)
    {
        Chassis = chassis;
    }

    public void AddDashboard(Dashboard dashboard)
    {
        Dashboard = dashboard;
    }
}
```

<p>I'm going to leave out the implementations of some of the components, like <code>IChassis</code>, <code>Seat</code> and <code>Dashboard</code> for the sake of brevity.</p>

<p>The <code>Car</code> is not responsible for building itself. The assembly line is, so let's encapsulate that in a class:</p>

<pre class="lang-cs prettyprint-override"><code>public class CarAssembler
{
    protected List<IAssemblyPhase> Phases { get; private set; }

    public CarAssembler()
    {
        Phases = new List<IAssemblyPhase>()
        {
            new ChassisAssemblyPhase(),
            new DashboardAssemblyPhase(),
            new SeatAssemblyPhase()
        };
    }

    public void Assemble(Car car)
    {
        foreach (IAssemblyPhase phase in Phases)
        {
            phase.Assemble(car);
        }
    }
}
</code>```

The important distinction here is that the CarAssembler has a list of assembly phase objects that implement IAssemblyPhase. You now are dealing explicitly with public methods, meaning each phase can be tested by itself, and your code quality tool is happier because you aren't stuffing so much into one single class. The assembly process is dead simple too. Just loop over the phases and call Assemble passing in the car. Done. The IAssemblyPhase interface is also dead simple with just a single public method that takes a Car object:

public interface IAssemblyPhase
{
    void Assemble(Car car);
}
```

<p>Now we need our concrete classes implementing this interface for each specific phase:</p>

<pre class="lang-cs prettyprint-override"><code>public class ChassisAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        car.AddChassis(new UnibodyChassis());
    }
}

public class DashboardAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        Dashboard dashboard = new Dashboard();

        dashboard.AddComponent(new Speedometer());
        dashboard.AddComponent(new FuelGuage());
        dashboard.Trim = DashboardTrimType.Aluminum;

        car.AddDashboard(dashboard);
    }
}

public class SeatAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
    }
}
</code>```

Each phase individually can be pretty simple. Some are just one liners. Some might be just blinding adding four seats, and another has to configure the dashboard before adding it to the car. The complexity of this long drawn out process is split into multiple, reusable classes that are easily testable.

Even though you said the order doesn't matter right now, it might in the future.

To finish this off, let's look at the process for assembling a car:

Car car = new Car();
CarAssembler assemblyLine = new CarAssembler();

assemblyLine.Assemble(car);
```

You can sub class CarAssembler to assemble a specific kind of car, or truck. Each phase is one unit within a larger whole, making it easier to reuse code.

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

If deciding what I wrote needs to be rewritten was a black mark on my career, then I would be working as a ditch digger right now, and you shouldn't take any of my advice. :)

Software engineering is an eternal process of learning, applying, and then re-learning. Just because you decide to rewrite your code doesn't mean you're going to get fired. If that were the case, there would be no software engineers.

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed?

What you have outlined is not the One True Way, however bear in mind that code metrics are also not the One True Way. Code metrics should be viewed as warnings. They can point to maintenance problems in the future. They are guidelines, not laws. When your code metrics tool points something out, I would first investigate the code to see if it properly implements the SOLID principals. Many times refactoring code to make it more SOLID will satisfy the code metrics tools. Sometimes it doesn't. You have to take these metrics on a case by case basis.

Title: Reducing the complexity of a class

Body:
The long sequence of operations seems like it should be its own class, which then needs additional objects to perform its duties. It sounds like you are close to this solution. This long procedure can be broken down into multiple steps or phases. Each step or phase could be its own class that exposes a public method. You would want each phase to implement the same interface. Then your assembly line keeps track of a list of phases.

To build on your car assembly example, imagine the Car class:

public class Car
{
    public IChassis Chassis { get; private set; }
    public Dashboard { get; private set; }
    public IList<Seat> Seats { get; private set; }

    public Car()
    {
        Seats = new List<Seat>();
    }

    public void AddChassis(IChassis chassis)
    {
        Chassis = chassis;
    }

    public void AddDashboard(Dashboard dashboard)
    {
        Dashboard = dashboard;
    }
}

I'm going to leave out the implementations of some of the components, like IChassis, Seat and Dashboard for the sake of brevity.

The Car is not responsible for building itself. The assembly line is, so let's encapsulate that in a class:

public class CarAssembler
{
    protected List<IAssemblyPhase> Phases { get; private set; }

    public CarAssembler()
    {
        Phases = new List<IAssemblyPhase>()
        {
            new ChassisAssemblyPhase(),
            new DashboardAssemblyPhase(),
            new SeatAssemblyPhase()
        };
    }

    public void Assemble(Car car)
    {
        foreach (IAssemblyPhase phase in Phases)
        {
            phase.Assemble(car);
        }
    }
}

The important distinction here is that the CarAssembler has a list of assembly phase objects that implement IAssemblyPhase. You now are dealing explicitly with public methods, meaning each phase can be tested by itself, and your code quality tool is happier because you aren't stuffing so much into one single class. The assembly process is dead simple too. Just loop over the phases and call Assemble passing in the car. Done. The IAssemblyPhase interface is also dead simple with just a single public method that takes a Car object:

public interface IAssemblyPhase
{
    void Assemble(Car car);
}

Now we need our concrete classes implementing this interface for each specific phase:

public class ChassisAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        car.AddChassis(new UnibodyChassis());
    }
}

public class DashboardAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        Dashboard dashboard = new Dashboard();

        dashboard.AddComponent(new Speedometer());
        dashboard.AddComponent(new FuelGuage());
        dashboard.Trim = DashboardTrimType.Aluminum;

        car.AddDashboard(dashboard);
    }
}

public class SeatAssemblyPhase : IAssemblyPhase
{
    public void Assemble(Car car)
    {
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
        car.Seats.Add(new Seat());
    }
}

Each phase individually can be pretty simple. Some are just one liners. Some might be just blinding adding four seats, and another has to configure the dashboard before adding it to the car. The complexity of this long drawn out process is split into multiple, reusable classes that are easily testable.

Even though you said the order doesn't matter right now, it might in the future.

To finish this off, let's look at the process for assembling a car:

Car car = new Car();
CarAssembler assemblyLine = new CarAssembler();

assemblyLine.Assemble(car);

You can sub class CarAssembler to assemble a specific kind of car, or truck. Each phase is one unit within a larger whole, making it easier to reuse code.

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

If deciding what I wrote needs to be rewritten was a black mark on my career, then I would be working as a ditch digger right now, and you shouldn't take any of my advice. :)

Software engineering is an eternal process of learning, applying, and then re-learning. Just because you decide to rewrite your code doesn't mean you're going to get fired. If that were the case, there would be no software engineers.

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed?

What you have outlined is not the One True Way, however bear in mind that code metrics are also not the One True Way. Code metrics should be viewed as warnings. They can point to maintenance problems in the future. They are guidelines, not laws. When your code metrics tool points something out, I would first investigate the code to see if it properly implements the SOLID principals. Many times refactoring code to make it more SOLID will satisfy the code metrics tools. Sometimes it doesn't. You have to take these metrics on a case by case basis.


答:
The key portion of his position is strive towards, not achieve. It's a question to if you want to spend time polishing variable names and documentation or you got it working and just pushed the code. I guess people would rather write some new fun feature than clean up dead code.

About the specific source you linked. From a quick look at angular the majority of the comments were public API documentation which he specifically called out as good(page 59 of my copy). There also seem to be a bunch of them that were referencing specific changes and linking back to the related issue like

```<code>//Encode angle brackets to prevent input from being sanitized to empty string #8683
</code>```

The deferred.js example does seem to have a fair bit of issues though with commented out code and a couple of places where it looks like the comment and the implementation don't match. It too has a number of comments that reference either the promises spec which are valuable.

It's all open source, if you think you could improve it, get involved and send them a pull request. The next guy will thank you.

Body:
The key portion of his position is strive towards, not achieve. It's a question to if you want to spend time polishing variable names and documentation or you got it working and just pushed the code. I guess people would rather write some new fun feature than clean up dead code.

About the specific source you linked. From a quick look at angular the majority of the comments were public API documentation which he specifically called out as good(page 59 of my copy). There also seem to be a bunch of them that were referencing specific changes and linking back to the related issue like

//Encode angle brackets to prevent input from being sanitized to empty string #8683

The deferred.js example does seem to have a fair bit of issues though with commented out code and a couple of places where it looks like the comment and the implementation don't match. It too has a number of comments that reference either the promises spec which are valuable.

It's all open source, if you think you could improve it, get involved and send them a pull request. The next guy will thank you.


答:
Not always big companies obey rules, even though the rules are for the benefit of people.

Similar situations rise back in the times when Internet Explorer (Microsoft) do not follow all the rules of World Wide Web Consortium. Some old versions of IE have some implementations for JavaScript and CSS which are working differently than the W3Consortium definitions, which cause designers to deal with Browser-based exceptions.

So being a big company or being a product of a big company or being a big open-source project would not mean it will obey the standards.

Standards are for making our life easier. Same is true for clean code rules, though some people find some rules pointless or unnecessary. But that do not mean those rules are pointless.

Think about the situations below:

You are working with 10+ developers on a project. You use version controlling and every developer have to work on many files. You have to use a class/module written by 5 different developer. The class/module is a quite long script and you have to figure out how it works so you can use it correctly. Would you prefer a well documented cod that cost you less time to understand or a long code with proper naming?

In your project, you need a module that will do a single job for you. You found an open-source project that is great. But unfortunately it is 10.000+ lines long and you have to figure out how you should use it. It have long explanatory variable names but (since it was not you who have written the code) no docstring.Would you prefer reading the whole project?

You need a module and get an open-source package which have a great on-site documentation. Then you start using it and a few weeks later boooom! The open-source project have a bug that effects your situation. You open a ticket but unfortunately, either the project is no longer supported and developed or the team is so busy that they scheduled your bug fix to a laterer unknown date. You open the source code. It have finely named variables and functions, but have no comments. So you have no idea where to start searching.

So, having self explanatory names is good. Having comments are good too but having both is better. Some big projects may refuse to obey clean code rules but that do not make those rules useless. Even Microsoft and other big companies sometimes do not obey the rules and that would make you nervous when you need those rules had applied. On that time, you understand how important those rules are.


答: Commenting is good - writing self-documenting code is just better. Usually, commenting takes less time than writing self documenting code. People working on open source project, even some of the big ones, are likely not to get paid for that, and contribute in their free time, so some of them might take the easier way, instead of keeping high standards like they would in their day job. Sometimes it's just pragmatic to minimize efforts even at cost of quality.</p>


问:
Efficient 2d per pixel lighting on Android
I am trying to create a simple 2d game to learn on my own. My current task is creating a lighting scheme.

My goal is to make the screen appear dark except where I create lights. I have a light class that only tracks the position and radius of the light. The code I feel I need help in improving is my per pixel lighting of images that come into the lights radius.

The code I have loads two images. The true image and a bumpmap. It also creates to a copy of the original to be the image to be modified by the light (referencing the originals pixels) and drawn. My code also sets two arrays. One holds the originals pixels to have the rgb pulled from them later. The other stores the calculated normals of the pixels to be used later in the class.

My problem is the update method thatgoes through each pixel using the position, dot product and normals to determine how the light shades the pixel. The update method pulls the frame rate from 60 to around 10 on a single 100x100 image.

I'm expecting to be told it's too much for an Android and better off used on a desktop game, but is that a correct assumption? If so, what are my alternatives? Code in question below.

package com.sevensoftware.simple2d;
import org.apache.http.*;
import android.graphics.*;
import android.content.*;
import android.util.*;

public class MyImage
{
  Bitmap image;
  Bitmap imageC;

  private Bitmap imageB;

  private int width;

  private int height;

  private int[][] map;

  private Point[][] nmap;

  private int power;

  private double softness;
  public MyImage(String name, Context context){

      //Load display image as original reference
      image = ImageLoader.loadImage(name,context);

      width = image.getWidth();
      height = image.getHeight();

      //Create a copy of display image to be our modifyable image
      imageC = image;
      //imageC.setConfig(Bitmap.Config.ARGB_8888);
      //Load Bumpmap
      Log.d("@myImage","loading bumpmap");
      imageB = ImageLoader.loadImage(name+"b", context);
      Log.d("@myImage","loaded bumpmap");
      power = 14;
      softness = Math.pow(2,power);
      map = new int[height][width];
      nmap = new Point[height][width];
      //Create normals
      createNormals();

  }

  public void setImage(Bitmap newImage){
      image = newImage;
  }

  public Bitmap getImage()
  {

      return imageC;
  }

  public int getHeight()
  {

      return height;
  }

  public int getWidth()
  {

      return width;
  }

  private void createNormals(){
      Log.d("@myImage","beginning normals");
      for(int i = 0; i < height; i++){
          for(int j = 0; j < width; j++){
              int c = (imageB.getPixel(j,i)>>16) &0xff;

              map[i][j] = c;

              nmap[i][j] = new Point(c, c);
          }
      }
      for(int i = 0; i < height; i++){
          for(int j = 0; j < width; j++){
              if(i==0|i==height-1|j==0|j==width-1){
                  continue;
                  }
              nmap[i][j].x = map[i][j-1]-map[i][j+1];
              nmap[i][j].y = map[i-1][j]-map[i+1][j];
              }
          }

      Log.d("@myImage","Created normals");

  }

  public void update(Light light, int imagePosX, int imagePosY){

      Log.d("@myImage","beginning update");
      int lx = light.x;
      int ly = light.y;
      int rad = light.radius;

      for(int i = 0; i < height; i++){
          for(int j = 0; j < width; j++){
      //normal vectors
      double AX = nmap[i][j].x;
      double AY = nmap[i][j].y;
              Log.d("@myImage","retrieved normal vetors");

      //light vector
      double BX = lx - (imagePosX+j);
      double BY = ly - (imagePosY+i);
              Log.d("@myImage","light vectors complete");

      //Dot product
      double dp = AX*BX + AY*BY;
              Log.d("@myImage","dp complete");

      int pixel = image.getPixel(j,i);
              Log.d("@myImage","got pixel");
      //int a = (pixel>>24) & 0xff;
      int r = (pixel>>16) & 0xff;
      int g = (pixel>>8) & 0xff;
      int b = (pixel) & 0xff;
              Log.d("@myImage","found rgb");

      double dist = Math.sqrt(BX * BX + BY * BY);
      double percent = (dp+softness/2)/softness;
      double percent2 = dist/rad;

      int lumen = (int)(percent*255);
      int shade = (int)(percent2*255);

      r+=lumen;
      g+=lumen;
      b+=lumen;
      r-=shade;
      g-=shade;
      b-=shade;

      if(r<0){r=0;}
      if(g<0){g=0;}
      if(b<0){b=0;}
      if(r>255){r=255;}
      if(g>255){g=255;}
      if(b>255){b=255;}

      Log.d("@myImage","attempting to set pixel");
      imageC.setPixel(j,i,Color.argb(255,r,g,b));
      Log.d("@myImage", "updated pixel");
      }
      }

  }
}
```

答:
There are a couple of things in this code that strike me as wrong or inefficient:

First, imageC = image; //Create a copy of display image to be our modifyable image doesn't actually create a copy of the image. It creates a copy of the reference to the image, hence you are modifying the actual image, rather than a copy. This is actually a thing throughout Java, only primitive values can be copied like this, objects require more work. In particular the correct way to make a copy of a bitmap is described here (ignore the accepted answer, and look at the highest-voted one instead).

Second, setPixel and getPixel are native methods that do quite a bit of stuff. There are much more performant bulk methods for that - setPixels and getPixels. It would be best to get all pixels you need in the beginning of the method and set them all in the end, after the computation is done.


问:
Usefulness of the Command CanExecute as it exists in WPF
I want to question the usefulness of the CanExecute functionality in WPF (defined in the ICommand interface). As I think that you can achieve the same functionality thing without this feature I ask myself why it is there in the first place.

My question is: If I build a new UI framework like WPF from scratch and I have to decide whether to include something similar to CanExecute, what are the arguments against or in favor of such a feature?

At the moment my opinion that if you favor simplicity this feature should be excluded as similar functionality can easily be achieve with an additional view-model property representing whether the command can currently be executed. Maybe my assumption is wrong and CanExecute really is an elegant feature, in this case I would ask you to provide convincing arguments.

答:
CanExecute has a couple of benefits over adding an IsEnabled property:

Each UI element that is bound to the command only needs 1 binding instead of 2 (this is both less work and, more importantly, less error prone).  It is common to have multiple views for a viewmodel or to have multiple UI elements bound to a single command (context menus are a prime example).

The CommandManager will automatically call CanExecute to update the state of the button which means you don't need to manually track and fire property change events for IsEnabled.  This is particularly convenient if your CanExecute depends on multiple conditions.

I would argue that adding a second property to separately track CanExecute increases complexity.

Also consider that other programmers who are familiar with MVVM will expect the Command to provide a CanExecute function and will be surprised when it does not.


问:
Is trait composition an good practice?
So, I am now dealing with this relatively new codebase which uses, and sometimes feels like it abuses traits. Since I have been exposed to trait usage in a rather limited fashion, I was wondering whether the way they are using them makes sense. I believe they are preferring to use traits when good old inheritance would work just as well.

Here is an example of what I am talking about:

trait CrudTrait
{
  use FindTrait;
  use ExistsTrait;
  use UpdateTrait;
}
```

<p>Then, the trait is used more or less the following fashion:</p>

```class <EntityName>ServiceAbstract extends ServiceAbstract
{
  use CrudTrait;
}
```

I can't think of a reason why something like this is necessarily better than just making such methods class members. At the end of the day, these particular traits are designed in such a way that they cannot be re-used horizontally.

Is there any reason why this could better than just attaching the methods to the parent class of the hierarchy?. I am starting to believe that trait abuse could be a code smell here.

答:
From what you've described, I'd have to agree that inheritance seems like a better approach.  But that opinions is based on knowing virtually nothing about the code base.

Traits essentially provide a way to do "multiple inheritance", and yes it can sometimes be useful.  Say for example you have a child class already inheriting from a parent, but there is another core set of functionality that needs to be shared all throughout the inheritance tree.

If the problem can be solved with inheritance alone though, that should always be your first choice.

Title: Is trait composition an good practice?


问:
Licensing for artistic work used inside GPLv3 licensed software
I'm a volunteer for a non-profit organization and am helping them develop a free open source Android application that will be licensed under GPLv3.

We are going to use the logo and some other graphics files from the organization and are wanting to use licensing of this artistic work to protect ourselves from anyone doing damage to the reputation of the organization.

What license would you suggest us using for our artistic work? Thinking outside of the box, is there another approach that would be better for us? Any thoughts more in general about what we can do to protect the organization?

答:
I have gotten help from FSF licensing and they suggest using the GPLv3 to license the art as well as the code.

After asking this question:

i'm a volunteer for a non-profit organization and am helping them
  develop a free open source Android app that i hope will be licensed
  under GPLv3

We are going to use the logo and some other graphics files from the
  organization and are wanting to use licensing of this artistic work to
  protect ourselves from anyone doing damage to the reputation of the
  organization

What license would you suggest us using for our artistic work and also
  the code itself? (Any thoughts more in general about what we can do to
  protect the organization?)

I got this response back:

GPLv3 is an excellent choice here for both the code and the art. Section
  7 of GPLv3 permits that your organization place additional terms which
  will help protect the work:

Section 7.b allows your organization to add terms "... Requiring
  preservation of specified reasonable legal notices or author
  attributions in that material or in the Appropriate Legal Notices
  displayed by works containing it ..."

Section 7.c allows your organization to add terms "... Prohibiting
  misrepresentation of the origin of that material, or requiring that
  modified versions of such material be marked in reasonable ways as
  different from the original version ..."

Section 7.d allows your organization to add terms "... Limiting the use
  for publicity purposes of names of licensors or authors of the material
  ..."

And section 7.e allows your organization to add terms "... Declining to
  grant rights under trademark law for use of some trade names,
  trademarks, or service marks ..."

I hope this is of help. Please feel free to write back with further
  questions.

I'm grateful for the service that they provide at the FSF (Free Software Foundation) and i hope me posting this help someone else too


答: I don't know if this is possible for you, but I'd be thinking about using a more data oriented approach.  The idea is that you capture some (declarative) expression of rules & constraints, operations, dependencies, state, etc...  Then your classes and code are more generic, oriented around following the rules, initializing current state of instances, performing operations to change state, by using the declarative capture of rules and state changes rather than using code more directly.  One might use data declarations in the programming language, or, some DSL tooling, or a rules or logic engine.</p>

Title: Reducing the complexity of a class

Body:
I have looked at some answers and searched on Google, but I could not find anything helpful (i.e., that wouldn't have awkward side effects).

My problem, in abstract, is that I have an object and need to perform a long sequence of operations on it; I think of it as a sort of assembly line, like building a car.

I believe these objects would be called Method Objects.

So in this example at some point I would have a CarWithoutUpholstery on which I would then need to run installBackSeat, installFrontSeat, installWoodenInserts (the operations do not interfere with one another, and might even be done in parallel). These operations are performed by CarWithoutUpholstery.worker() and yield a new object which would be a CarWithUpholstery, on which I would then run maybe cleanInsides(), verifyNoUpholsteryDefects(), and so on.

The operations in a single phase are already independent, i.e., I am already grappling with a subset of them that may be executed in any order (front and rear seats may be installed in any order).

My logic currently uses Reflection for simplicity of implementation.

That is, once I have a CarWithoutUpholstery, the object inspects itself for methods called performSomething(). At that point it executes all these methods:

```<code>myObject.perform001SomeOperation();
myObject.perform002SomeOtherOperation();
...
</code>```

while checking errors and stuff. While order of operation is unimportant, I have assigned a lexicographic order in case I ever discover some order is important after all. This contradicts YAGNI, but it costed very little - a simple sort() - and it could save a massive method renaming (or introducing some other method of performing tests, e.g. an array of methods) down the line.

A different example

Let us say that instead of building a car I have to compile a Secret Police report on somebody, and submit it to my Evil Overlord. My final object will be a ReadyReport. To construct it I start by gathering basic information (name, surname, spouse...). This is my Phase A. Depending on whether there is a spouse or not, I may then have to proceed to phases B1 or B2, and gather sexuality data on one or two people. This is made of several different queries to different Evil Minions controlling night life, street cams, sex shop sales receipts and what not. And so on and so forth.

If the victim has no family, I will not even enter the GetInformationAboutFamily phase, but if I do, then it's irrelevant whether I first target the father or the mother or the siblings (if any). But I cannot do that if I haven't performed a FamilyStatusCheck, which therefore belongs to an earlier phase.

It all works wonderfully...

if I need some additional operation I only need to add a private method,

if the operation is common to several phases I can have it inherited from a superclass,

operations are simple and self-contained. No value from one operation is ever required by any of the others (operations that do are performed in a different phase),

objects down the line do not need to perform many tests since they could not even exist if their creator objects hadn't verified those conditions in the first place. I.e., when placing inserts in the dashboard, cleaning the dashboard and verifying the dashboard, I needn't verify that a dashboard is actually there.

it allows for easy testing. I can easily mock a partial object and run any method on it, and all operations are deterministic black boxes.

...but...

The problem arose when I added one last operation in one of my method objects, which caused the overall module to exceed a mandatory complexity index ("less than N private methods").

I have already taken the matter upstairs and suggested that in this case, the wealth of private methods is not a telltale of disaster. The complexity is there, but it's there because the operation is complex, and actually it's not all that complex - it's just long.

Using the Evil Overlord example, my problem is that the Evil Overlord (aka He Who Shall Not Be Denied) having requested all dietary information, my Dietary Minions telling me that I need to query restaurants, kitchenettes, street vendors, unlicensed street vendors, greenhouse owners etc., and the Evil (sub)Overlord - familiarly known as He Who Also Shall Not Be Denied - complaining that I'm performing too many queries in the GetDietaryInformation phase.

Note: I am aware that from several points of view this is not a problem at all (ignoring possible performance issues etc.). All that's happening is that a specific metric is unhappy, and there is justification for that.

What I think I could do

Apart from the first, all these options are doable and, I think, defensible.

I have verified that I can be sneaky and declare half my methods protected. But I'd be exploiting a weakness in the testing procedure, and apart from justifying myself when caught, I don't like this. Also, it's a stopgap measure. What if the number of required operations doubles? Unlikely, but what then?

I can split arbitrarily this phase into AnnealedObjectAlpha, AnnealedObjectBravo and AnnealedObjectCharlie, and have one third the operations being performed at each stage. I am under the impression that this actually adds complexity (N-1 more classes), with no benefit except for passing a test. I can of course hold that a CarWithFrontSeatsInstalled and a CarWithAllSeatsInstalled are logically successive stages. The risk of a Bravo method being later required by Alpha is small, and even smaller if I play it well. But still.

I can bunch different operations, remotely similar, in a single one. performAllSeatsInstallation(). This is only a stopgap measure and it does increase the complexity of the single operation. If I ever need to do operations A and B in a different order, and I have packed them inside E = (A+C) and F (B+D), I'll have to unbundle E and F and shuffle the code around.

I can use an array of lambda functions and neatly sidestep the check altogether, but I find that clunky. This is however the best alternative so far. It would get rid of reflection. The two problems I have is that I would probably be asked to rewrite all method objects, not only the hypothetic CarWithEngineInstalled, and while that would be very good job security, it really doesn't appeal all that much; and that the code coverage checker has issues with lambdas (which are solvable, but still).

So...

Which, you think, is my best option?

Is there a better way I haven't considered? (perhaps I'd better come clean and ask directly what is it?)

Is this design hopelessly flawed, and I'd better admit defeat and ditch - this architecture altogether? Not good for my career, but would writing ill-designed code be any better in the long term?

Is my current choice actually the One True Way, and I need to fight to get better quality metrics (and/or instrumentation) installed? For this last option I'd need references... I can't just wave my hand at the @PHB while murmuring These aren't the metrics you're looking for. No matter how much I'd like to be able to


问:
Process for TFS task handoff between users?
If I have a story with multiple tasks for different users, is there a good process flow when a task is dependent on previous tasks to ensure subsequent assigned users are aware that they now have a task ready to be worked on?

Assume that all tasks are already assigned to appropriate users.

Basically when the developer finishes their coding and checks in, there is another task following it for a different user to do some additional work.

Looking for something where the 2nd user will simply not see their task until the dependent task is done.

My one thought is:

A status for the 2nd TFS task that is "Not Ready" and a TODO query that excludes these.

As a matter of process, if a developer completes a task, they should look at the story to see if there is a task following it, and if it is "Not Ready" change it to "New".

Users will use the TODO query to review tasks they have to complete, and the task changing from "Not Ready" to "New" will cause it to show up in their query.

Can I rely on ordering of tasks to be consistent within a story?  I.e. so it is clear when completing a task, which one is clearly "next" without setting specific dates. (We usually don't set dates to tasks, and plan by assigning to sprints.)  I've never noticed if tasks have a consistent ordering within a story in the absence of any priorities, or if it is just a bucket with arbitrary ordering.

Any pitfalls to this?

Obviously the one thing not ideal is it depends on a human process as a matter of habit. I'm not extremely concerned about that, but certainly not ideal.

Open to ideas for other processes to accomplish the same.

I'd rather avoid custom scripting behaviors in TFS, and just stick with customization via configuration.

To clarify, this is TFS within Visual Studio Online.

答:
Given that the tasks are sequential, you can leverage parent-child work item links.

Have one parent work item that represents the story.  That work item can have child tasks each assigned to the person responsible for doing them.

Then the parent work item can be assigned to whomever is currently working on their task.  When they finish, they can mark their task as done and assign the parent item to the next person in line.  When the last person finishes, they can mark the parent work item as done.


问:
MVC controller and decoupling explained
In this article you can see that View has (uses or aggregates ) controller and ConcreteView has Concrete model.   </p>

```<code>public abstract class View
{
    public abstract void Update();
    private readonly Controller Controller;
    protected View()
    {
    }
    protected View(Controller controller)
    {
        Controller = controller;
    }
    public void ContextInterface()
    {
        Controller.AlgorithmInterface();
    }
}

public class ConcreteView : View
{
    private object ViewState;
    private ConcreteModel Model { get; set; }
    public ConcreteView(ConcreteModel model)
    {
        Model = model;
    }
    public override void Update()
    {
        ViewState = Model.ModelState;
    }
}
</code>```

<p>So this is considered classic MVC by GoF. I don't see where how view is not aware of the model and vice versa. I mean, what if we just put model pointer in the view as it is now and we don't use controller. What is the problem here? What that Strategy pattern does for me (see in the article). Plus as much as I know, in MVC the view should not know about the model and model about the view. So if you have a reference in the view on the model, doesn't it mean they know about each other? </p>

答:
The View needs the Model in order to update its view of the model (Model here could be an abstraction or a concretion).  The Model knows that there may be abstract Views that are interested in updates, but the Model does not know the concrete type of View(s).

The Controller changes the model.  If there's an element of the View that enables modification, then the View will need a Controller.  Otherwise, the View would not need a Controller.

Title: MVC controller and decoupling explained


答:
Your MVC view should actually be bound to an interface not to a concrete model. This allows you to perform the decoupling by which the view can accept any IModel that adheres to its expectations. To put it into context using your code:

```<code>public abstract class View
{
    public abstract void Update();
    private readonly IController Controller;
    protected View()
    {
    }
    protected View(IController controller)
    {
        Controller = controller;
    }
    public void ContextInterface()
    {
        Controller.AlgorithmInterface();
    }
}

public class ConcreteView : View
{
    private object ViewState;
    private IModel Model { get; set; }
    public ConcreteView(IModel model)
    {
        Model = model;
    }
    public override void Update()
    {
        ViewState = Model.ModelState;
    }
}
</code>```

In several frameworks you may not have this kind of granular control over the definition of the view, but the principles don't really change. If all of your code is against an interface (re: contract), then the concrete implementation no longer matters so long as all objects adhere to the contracts. When dealing with framework objects the interfaces may not be available, and you may have to resort to using this same technique with the framework base classes instead.

Title: MVC controller and decoupling explained

Body:
In this article you can see that View has (uses or aggregates ) controller and ConcreteView has Concrete model.   </p>

```<code>public abstract class View
{
    public abstract void Update();
    private readonly Controller Controller;
    protected View()
    {
    }
    protected View(Controller controller)
    {
        Controller = controller;
    }
    public void ContextInterface()
    {
        Controller.AlgorithmInterface();
    }
}

public class ConcreteView : View
{
    private object ViewState;
    private ConcreteModel Model { get; set; }
    public ConcreteView(ConcreteModel model)
    {
        Model = model;
    }
    public override void Update()
    {
        ViewState = Model.ModelState;
    }
}
</code>```

<p>So this is considered classic MVC by GoF. I don't see where how view is not aware of the model and vice versa. I mean, what if we just put model pointer in the view as it is now and we don't use controller. What is the problem here? What that Strategy pattern does for me (see in the article). Plus as much as I know, in MVC the view should not know about the model and model about the view. So if you have a reference in the view on the model, doesn't it mean they know about each other? </p>

Body:
Your MVC view should actually be bound to an interface not to a concrete model. This allows you to perform the decoupling by which the view can accept any IModel that adheres to its expectations. To put it into context using your code:

public abstract class View
{
    public abstract void Update();
    private readonly IController Controller;
    protected View()
    {
    }
    protected View(IController controller)
    {
        Controller = controller;
    }
    public void ContextInterface()
    {
        Controller.AlgorithmInterface();
    }
}

public class ConcreteView : View
{
    private object ViewState;
    private IModel Model { get; set; }
    public ConcreteView(IModel model)
    {
        Model = model;
    }
    public override void Update()
    {
        ViewState = Model.ModelState;
    }
}

In several frameworks you may not have this kind of granular control over the definition of the view, but the principles don't really change. If all of your code is against an interface (re: contract), then the concrete implementation no longer matters so long as all objects adhere to the contracts. When dealing with framework objects the interfaces may not be available, and you may have to resort to using this same technique with the framework base classes instead.


问:
DI and hypothetical readonly setters in C#
Sometimes I would like to declare a property like this:

```<code>public string Name { get; readonly set; }
</code>```

I am wondering if anyone sees a reason why such a syntax shouldn't exist. I believe that because it is a subset of "get; private set;", it could only make code more robust.

My feeling is that such setters would be extremely DI friendly, but of course I'm more interested in hearing your opinions than my own, so what do you think?

I am aware of 'public readonly' fields, but those are not interface friendly so I don't even consider them. That said, I don't mind if you bring them up into the discussion

Edit

I realize reading the comments that perhaps my idea is a little confusing. The ultimate purpose of this new syntax would be to have an automatic property syntax that specifies that the backing private field should be readonly. Basically declaring a property using my hypothetical syntax

```<code>public string Name { get; readonly set; }
</code>```

would be interpreted by C# as:

```<code>private readonly string name;
public string Name
{
    get
    {
        return this.name;
    }
}
</code>```

And the reason I say this would be DI friendly is because when we rely heavily on constructor injection, I believe it is good practice to declare our constructor injected fields as readonly.

答:
The C# team has considered that this would be a very useful feature, and that's why in C# 6, they implemented it (just a little different from your proposal).

Getter-only auto-properties

This new kind of properties are getter-only, but can be set either inline or in the constructor. This means they are backed internally by a readonly field.

Instead of declaring a property as readonly set, you simply not declare it.

Inline assignment

```<code>public class Customer
{
    public string First { get; } = "Jane";
    public string Last { get; } = "Doe";
}
</code>```

Constructor assignment

```<code>public class Customer
{
    public string Name { get; }
    public Customer(string first, string last)
    {
        Name = first + " " + last;
    }
}
</code>```

You can read about this and other new features of C# 6 in the Roslyn wiki in GitHub.

Body:
The C# team has considered that this would be a very useful feature, and that's why in C# 6, they implemented it (just a little different from your proposal).

Getter-only auto-properties

This new kind of properties are getter-only, but can be set either inline or in the constructor. This means they are backed internally by a readonly field.

Instead of declaring a property as readonly set, you simply not declare it.

Inline assignment

public class Customer
{
    public string First { get; } = "Jane";
    public string Last { get; } = "Doe";
}

Constructor assignment

public class Customer
{
    public string Name { get; }
    public Customer(string first, string last)
    {
        Name = first + " " + last;
    }
}

You can read about this and other new features of C# 6 in the Roslyn wiki in GitHub.

ContentLicense: CC BY-SA 4.0


问:
Delphi vs C# for GUI programming
I'm coming from PHP and Python background with little knowledge of C, I have done many web based application now I'm thinking of Desktop application for windows platform.

A friend told me to go for Delphi and others are saying C# is the best, well, what I'm looking for is

Simplicity

Productivity

Good API documentation

Speed

Drag and Drop

Multi threading & Good Network API

Thanks

答:
C# generally is going to have a larger user base, more development in the future, and the tools for RAD development through Visual Studio are unbelievable.

The syntax will be similar to that you used in PHP and C.

Visual Studio with its tools and IntelliSense is extremely productive.

MSDN

Again, VS tools + Intellisense, but speed really comes from a familiarity of your language and its features.

VS designer for WinForms, WPF.

System.Threading and System.Net

I do not have much experience with Delphi, and I am just speaking about my experiences with C# in general.  Where I work, I have extremely tight deadlines envisioned by non-programmers, and I am able to pump out line of business desktop applications extremely fast.  In the last three weeks, I went from specification to deployment on two winforms LOB applications.  The productivity for GUI development in C# with VS is just crazy.

Title: Delphi vs C# for GUI programming


问:
Is a memory of all possible permutations of a kilobyte block and pointers possible?
This is a hard enough idea to wrap my head around and I would greatly appreciate any edits/help to get it more readable for those in-the-know.

Is it theoretically possible to have a hard drive that has saved on it one copy of every possible binary permutation of one kilobyte and then have the rest of the system simply create pointers to these locations?

Would a system made such a way be any faster than simply having information stored directly?

To explain another way, say instead of having sentences:

"Hello, I'm Bob." and "That sandwich looks delicious."

...stored on the hard drive, we would have all permutations of the alphabet and other characters up to some number (say, 1000 characters or so), and then have store our sentences as something like:

[Pointer#21381723]

答:
As other posters have pointed out, at some point, the size of the pointer needed to index into your list of all possible values nullifies your gain.

However, some languages use a limited version of what you suggest in order to optimize memory usage.  Python uses string 'interning' to lessen the number of duplicate strings in memory.  You can find more information by searching for 'python string intern'.


答:
Composition is usually preferable to inheritance, unless you need substitutability.  Traits are one specific way to perform composition.  Usually you use traits when you need horizontal reusability, but it's also reasonable to use them for modularity, to break up a class that can't be broken up for some reason.

It's relatively rare that you can't just split up the class normally.  It's usually driven from an external requirement, like needing to provide all the parts of an API in one class.  Alternately, traits are often used to sort of assemble a compile-time configuration of a class, such as if you had multiple choices for a FindTrait, for example, that different customers would choose differently, even if your particular implementation only uses the one configuration.

Traits are probably under-utilized and not very well understood, because a lot of programmers' first and main languages don't have them.  They could well be abused in this particular code base.  However, in general, inheritance is much more likely to be overused than traits.  If traits are being used improperly here, it's highly likely that replacing it with inheritance would make it worse.

Title: Is trait composition an good practice?

Body:
So, I am now dealing with this relatively new codebase which uses, and sometimes feels like it abuses traits. Since I have been exposed to trait usage in a rather limited fashion, I was wondering whether the way they are using them makes sense. I believe they are preferring to use traits when good old inheritance would work just as well.

Here is an example of what I am talking about:

trait CrudTrait
{
  use FindTrait;
  use ExistsTrait;
  use UpdateTrait;
}
```

<p>Then, the trait is used more or less the following fashion:</p>

```class <EntityName>ServiceAbstract extends ServiceAbstract
{
  use CrudTrait;
}
```

I can't think of a reason why something like this is necessarily better than just making such methods class members. At the end of the day, these particular traits are designed in such a way that they cannot be re-used horizontally.

Is there any reason why this could better than just attaching the methods to the parent class of the hierarchy?. I am starting to believe that trait abuse could be a code smell here.


问:
Is Activity/Fragment already a presenter?
An Activity or a Fragment is where you handle the logic of updating views with model data. However, they are tighly coupled with the Android's framework.

Are these classes already presenters?

Bonus: Is it overengineering to design exclusive presenter classes that are not coupled with the framework?

Consider scenarios where classes like REST API client and local database manager (Both singleton injected via IoC container) are dependencies for a presenter

答:
A framework, by its nature, pervades your application, or better, is all around it, and you don't have much choice if you want to program Android.

By what I read on Wikipedia, yes, Activities/Fragments are presenters, being the middleman between the view and the core of your application. You could extract the "controller" part from them by taking out the listener implementations, but updating the views still requires knowing which value goes into which widget and how to set it... you have to get dirty with the framework at some point.

Even the implementation of your REST API client might be framework dependent, as Android has its own http connection tools IIRC, same for local db. What you can (and should!) surely make framework-independent is the core, business logic of your application (e.g. the board model and rules of a chess game, the "top scores" service, "save game" one...) In this core you would define also the interfaces (i.e. what you expect to get from them) of the REST client and db manager.

Like you say, the presenters should just be clients of such core API, but I don't see how they can be decoupled from the framework, as they're what binds your core with Android.


问:
Should I use MongoDB for reference data?
I have a need to implement a number of microservices that will provide validation and lookup services. Each will hold independent and (essentially) read-only reference data. In each case, the data would easily fit in a relational db. Given the size of the data, SQL Server would probably end up caching the blocks in memory. The data situation is:

little or no growth

infrequent updates

few (or no) joins required

small databases

hundreds or thousands of rows

But I need very fast access.

Communications between microservices will be via web calls exchanging JSON.

Given this, is there any performance advantage in using a NOSQL db, like Mongo, in this case?

SQL Server would be easier, but is happy to go Mongo if there is a reason. If 95% of the cost of the call is the call overhead and 5% is the actual data retrieval, then the DB tech probably does not make much difference.

More details:

The application we are building is based on a microservices architecture with (ultimately) 10s or 100s of services. The core data component will be significant (detailed information on 100,000s of members). It will be hosted primarily on SQL Server on Windows servers. Given the isolation level between services, each can use the most appropriate technology.

This question specifically relates to the reference data part of things.

答:
Given the size of the data and the frequency of updates, I would consider the choice of the database irrelevant: in order to get very fast access, you'll use caching anyway, which, from your description of the context, wouldn't be difficult to implement for all the data.

The major considerations would be:

The structure of the data. Is it better represented as a bunch of tables or rather documents?

The complexity of the data. If the data is simple enough, wouldn't Redis be another alternative? What about a flat file?

Reliability: although both SQL Server and MongoDB make it possible to replicate data on multiple servers, make sure you have enough expertise to set up and configure the environment.

Your purely subjective preferences. Microsoft? Oracle? Open source? Licensing is another important factor. In production, SQL Server—even its free variant—is usually hosted on Windows Server, which could quickly become too expensive for a small project.


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答: I'm a Chinese and we write code in English while we write the comments in Chinese.</p>


问:
How to deal with tremendous number of failing tests?
I'm working in the development of an old project written in Java. We have more than 10 million LOC and, even worse, more than 4000 functional tests.

The tests, scheduled by Hudson, are failing like mad with every bigger code change. Verification of the test failure - if it's a problem in the product or in the test, takes months. We cannot remove the old tests because we don't know what they are testing!

What we can do? How to proceed with such amount of legacy tests?

答:
If you don't know what they are testing, remove them until you do know. Tests are fluid things, if you remove a feature that is no longer required, then you should expect to have to change the test that tests that feature! So unless you know what the tests are testing, you have no hope of changing the codebase with them in place.

You can get the test system set up on developer's machines and run there so the devs can see what parts the tests are interacting with, hopefully provide this missing documentation, and become more familiar with the codebase that you are either not changing correctly, or no longer testing correctly.

In short - if your old tests are failing when you make changes, your code changes are not good. Use those tests as a means of education in how the system works.


答:
Abandon them.

I know it's hard to let go of something that was clearly a lot of effort to produce, but the tests aren't working for you, they're working against you. A test suite is supposed to give you confidence that the system does what it's supposed to do. If it doesn't do that, it's a liability instead of an asset. It doesn't matter whether the system or the tests are at fault - as long as running the test suite signals huge amounts of errors, it cannot fulfill its purpose.

What you need now is a new suite of tests that runs with no errors. That means it will initially have little coverage, in fact almost no coverage. Every time you fix or take the time to thoroughly understand something about your system, you reord that knowledge in a test. Over time, this will produce a new safety net that you can build on in the future. Trying to patch an old, ill-understood safety net is a time sink that is almost never worthwhile.

I would even advocate against transferring tests from the old suite to the new suite. Sure, some of them may succeed now, but is that because they are testing exactly what they are supposed to test, or just because some random shots always hit the target? Obviously you have to be pragmatic about what can and can't be done with the effort you have avaiable to spend, but you can't compromise on the principle that a test suite must run cleanly in order to do its job.

Title: How to deal with tremendous number of failing tests?

Body:
I'm working in the development of an old project written in Java. We have more than 10 million LOC and, even worse, more than 4000 functional tests.

The tests, scheduled by Hudson, are failing like mad with every bigger code change. Verification of the test failure - if it's a problem in the product or in the test, takes months. We cannot remove the old tests because we don't know what they are testing!

What we can do? How to proceed with such amount of legacy tests?


问:
Advantages of using .dll files over linking .cs files to projects (for my own generic helper classes / extension methods)
I have a helper project which I use in all the applications that I create. It contains some extension methods and a bunch of generic helper classes, controls etc. I update/extend the helper project from time to time. These are usually small and unrelated projects, and I am the only person working on all of them.

I tried two approaches for using it

add .cs files directly (Add as link) to each project where I use them

compile it as .dll and add it as reference

I see some benefits and drawbacks of these approaches.

The first one:

is simpler, because the helper classes get compiled into the exe file, therefore I can often very easily provide just a single .exe file that will work just fine. Because I add as link, I can be pretty sure that whenever I build any project that uses the helper, the helper files will be the latest version.

is even simpler, because I can separate the files, so that my extension methods that run fine on .NET 4.0 can be referenced separately from the ones that require .NET 4.5, which means that the app as a whole can run on .NET 4.0

Allows to debug through the code, with all the benefits of breakpoints etc etc...

doesn't seem to be 'best practice'

The second one:

appears to be the right approach, but:

requires me to deliver a separate .dll file, which for some reason is much more difficult for users (they tend to share my programs without the .dll, which then crashes on startup)

as it gets compiled into a single .dll, it will require the highest version of .NET - many of my users don't have .NET 4.5 and only some elements of my helper class require this, which means I can be forcing some people to update their systems for no reason

I also need to make sure that whenever I update any of my programs, I also deliver the .dll file - even though I don't know if it has been changed since the last version, or not (it could have been, but it could as well be the same version). I cannot see a simple way to determine that, without keeping track of assembly version, which is additional work. For now, when I update my programs, I only deliver updated exe, and I like to keep it small and low profile.

So, what is the actual benefit for using the .dll file here? Please note, that I am the only person editing code of all the applications and the helper files.

Also, to clarify - the apps are usually very little, whereas the code contained in the helper classes is completely generic to all of them (some simple string-comparison, paths or XML operations etc)

Actually, someone made me realize just now that there's a third option.
As I have the helper code in a separte project, I can add this project to solutions of each of my separate applications - which works kind of like 'Add as link' for single files, except I only add a single project...
But as noticed by Doc Brown, this essentially means that .dll will need to be added to the project anyway...

Yet another thing which is kind of in favour of not using the dll files is the ability to debug through the helper class actively...

答:
As a developer, I always like to include the reference of utility's solution to my application as it allows me debug the code (and spot possible bugs in Utility too!) plus any changes made to the utility are automatically included in the application.

So, actually the decision depends on how mature the Utility is!
If you are uncertain about the Utility bugs, then you should always include the .cs file of that utility to find out the bugs.. But if you are sure that Utility is mature enough and it will not be returning result with any bugs and there is no scope for enhancement in the Utility, you can go ahead and include the DLL file.


答:
Go and fix the tests.

Your biggest mistake is that you allowed tests to fail, and you obviously ignored it for a while. What you have is not "legacy tests" - you are working on a legacy code. And I consider every code written without tests to be legacy.

Verification of the test failure - if it's problem in product or in test, takes months. We cannot remove the old tests because we didn't know what they are testing!

It looks like there is a even bigger problem in your organization, since you are not working with clear requirements. I can not understand that you (or someone else) can't confirm the right behaviour.


问:
Implementing a complexity hiding layer
As part of the dependencies that the project I'm working on has, we use several core services. These services, to which we can't make big changes, are a big mess. Depending on the method we invoke, we need to convert our parameters (and return values) to different encodings, locales and time zones.

Since we generate these parameters in multiple places in our own code, we perform these conversions in multiple places. Some times where we generate them, before passing them around in our side; some times right before invoking the method in the core service. So the mess is spreading throughout our code, and I want to introduce a layer to isolate it.

My question is what's the best approach for that. Initially I thought of just creating a service/method corresponding to each service/method that we need to use. These methods would simply perform the conversion, delegate to the core services and perform conversion of the return value. But this seems somehow unwieldy.

Then I thought of using annotations, but I'm not completely sure of how to use them. And as I understand it, ideally I would need to annotate the invoked method. For instance, I could annotate the parameters with @converToUtc, and do the conversion in the annotation implementation. Is this correct? Of course, this is hard because it's not our code and it'll break code currently using those methods in projects other than our.

What's the best approach for this situation?

答:
The problem you are facing is an instance of a general problem that we quite often face in Software Engineering: Molding the tools to bring them to our specific problem domain by means of abstraction/conversion layers.

You have an application which solves a problem.  The entities that it contains, manages, and interacts with are entities that belong to the domain of the problem. They are all expressed in terms that are useful for solving the problem at hand, and they are "friendly" in that they allow you to focus on solving the problem rather than wasting time and polluting your code with conversions that have nothing to do with the problem at hand.

For as long as you own all of the code, that's all fine and dandy; but when you bring third party tools (libraries) into the picture, these tools have most probably not been written to work within your problem domain, so they require conversions which are often distracting, cumbersome, and error-prone.

What usually happens is that the inconveniences are minor, and we just cope with the tools that we are given.  But when the inconveniences are major, so much that they make our daily life considerably more difficult, or that the end result is more fragile and more error prone, then we do sometimes introduce abstraction/conversion layers between our code and the tools that we use.

These abstraction/conversion layers offer services to our code which are expressed in terms of our problem domain, and they delegate to the third-party tools, performing all the necessary conversions along the way.  When doing so, these layers tend to also abstract as much as possible of the peculiarities of the tools that we use, so that we can, in theory, replace a tool with a different tool by modifying only the abstraction/conversion layers, with no need to modify our core logic.

Regarding annotations, I do not see how they can help here.  First of all, if you do not own the source code of the target interfaces, then you cannot add annotations to them.  But even if you could somehow add annotations to the target interfaces, for the annotations to work you would have to embed some intermediate layer between your code and the target interfaces, which intercepts the calls, examines the annotations of the target methods, and performs the necessary conversions.  You could, perhaps, use the Spring Framework or something like the Castle Proxy's Interceptor mechanism to magically embed this intermediate layer between your code and the libraries, but it seems to me that you could just as easily write the intermediate layer in a traditional way, having intimate knowledge of the target interfaces, performing the conversions in a hard-coded, straightforward fashion, and also abstracting the interfaces of the libraries to suit your needs.

Title: Implementing a complexity hiding layer