How do you come up with names for your namespaces? - language-agnostic

I'll preface this by saying that I usually work in C#/.Net.
Normally, I use a naming scheme that puts common, reusable components into a namespace that reflects our organization and project-specific components into a namespace tied to the project. One of the reasons I do this is that I sometimes share my components with others outside my department, but within the organization. Project-specific namespaces are typically prefaced with the name or abbreviation of the department. When I reuse code between projects, I typically migrate it into one of the organization-based namespaces.
For example:
UIOWA.DirectoryServices contains classes that deal with the specific implementation of our Active Directory.
UIOWA.Calendar contains classes that deal with the University's master calendar.
LST.Inventory.Datalayer holds the classes implementing the data layer of the Learning Spaces Technology group inventory application.
I'm embarking on a project now for an entity that has a fuzzier connection to the Unviersity (a student group that runs a charity event) that has the potential to be sold outside of our University and, thus, it doesn't really fit into my normal naming conventions, i.e., the department is only the first customer of potentially many that might use the project.
My inclination is to go the organization naming route and create an "organizational project" name space for this application. I'd like to hear how others handle this and any advice you might have.
Thanks.
See also this related question about namespace organization.
EDIT
I ended up creating the org/project namespace UIOWA.MasterEvent and deriving further namespaces from there. Still interested in other opinions for future projects.

My department got his name changed thrice in the last five years, so we're all glad that someone decided against using namespaces with organisational names...
Our namespaces are organised by project names. Reusable stuff is put into the Toolbox namespace. Perhaps a bit crude, but it works quite well so far.

I'm a .NET developer, and I always use the organisational project namespace (com.bolidian.projectspace) because it guarantees uniqueness.

I use the organisation, followed by the product eg Acme.Crm. When grouping classes together in a subnamespace always use a plural or action so that it cant clash with a class. eg
Acme.Crm.Letters
Acme.Crm.Invoicing
I follow Microsoft's convention by not capitalising acronyms eg Crm instead of CRM, Sql instead of SQL - but that's more a personal preference.

Related

How to handle different customer versions in Angular 2 app?

We are developing a SaaS-application and currently facing the situation that different customers ask for different customizations. I have already googled and read a lot specifically about Multitenancy. I am also familiar with the Strategy Pattern.
But this still leaves me a bit confused about a good concept for an Angular 2+ application. Business logic is not gonna be the problem, as I can use Angular's dependency injection to load and use customized services for different customers. Also theming itself is not a problem, as we use Angular Material which has a nice theming engine build in. What does give me a headache are the templates itself. Of course I can use *ngIf and *ngSwitch within the HTML templates, but this is exactly the kind of code I want to avoid, because it will become horrifying once reaching 50+ customer versions.
Let's have a real life example. On a search-page all customers can search for objects and export single objects as a file download. One specific customer asks as to implement a mass export in a proprietary file format which needs a new button in the page, which obviously all the other customer should not see.
The three options I can think of for this scenario (and none of which I really like) are the following:
as mentioned before working in the template itself with *ngIf and/or *ngSwitch*
using the theming capabilities of Angular Material and working with css-only (display: none;)
maintaining multiple versions of the component (depending on the needs using component inheritance) and loading the correct version of the component depending on the user
All of them have obvious con's, just to name a few:
Nightmare to maintain once customer numbers grow and customizations become more frequent (think of a bigger component with 6 differentiations and 50 customers ...)
for now actually my favorite, but functionality not really disabled, just hidden (of course the back-end checks for permissions, but still more information is transferred to the users then necessary)
works well for the code-part of the components, but would mean to maintain massive amounts of duplicate template-code
I am sure we are not the first to tackle this issue. Am I overseeing any solution with less disadvantages? Are there any code patterns that I could apply here?
edit: after more discussion in our company we realized that there is another important point to this: some customers are hosted on their own servers, but most of them are being served from one central server. This means that the optional features have to detected and added at run-time, which implies some kind of awkwardness.
So our approach is to extend our existing licensing database to also contain the customer specific functionalities, which then obviously only that customer has a license for. Now the easy solution is to have a license endpoint and get all the licenses the customers has acquired, then every optional function can just sit in a simple single *ngIf. I appreciate that this is a simple and clean solution, but it offers the potential to find out some business facts about other customers of our company (by unobfuscating the code and finding additional endpoints etc.pp.). So probably combining this with server-side rendering would be the best solution I can think of right now.
Of course I don't have a clear cut solution that would totally fit your scenario, but here is an idea.
Divide your page into components that act as container regions.
For each customer create a customer configuration that would say
which atomic components goes in each region.
Create atomic components in which each component can be a single function isolated from the rest of the other components. Rely more on services to communicate between them. As an example for this atomic component is the button that create the new export in your example.
Create your page dynamically using ComponentFactory.
I have used the same approach before to customize a design toolbox based on a slide template (like powerpoint slides templates).
As for the options you mentioned, here are my 2 cents:
*ngIf and *ngSwitch, you can eliminate these if u create ur components dynamically and use granular or atomic components.
I don't think this would be a good approach in terms of architecture
and design. You are just manipulating the view css
If you use transclustion, this can minimize your code base if you
can group the components efficiently.
I hope this helps.

Namespace for (DDD) entities cutting across domains

I have a couple of business-related domains like Purchase, Marketing and Economy. Having the models arranged into a namespace* for each domain would be nice, but there are some entities cutting across domains, like an Item. How to organize those cross-cutting objects?
* = As in C#/Java/Python namespaces.
Since you have the concept of Bounded Context, you should not share domains between the namespaces. Actually, you should have one Item for each namespace that requires it, and each of those Item should have it's own fields as required by the context it is included.
As Eric Evans said, it is not a big deal replicate data in order to never share the same domain between contexts, but only data.
Determining whether you have the correct design will require some experience with the domain so you should check with your domain expert.
You may very well require a Shared Kernel for classes that are cross-cutting. You'll have to be careful that you do not abuse the shared kernel by placing too many generic / logical classes in there.
To add to what #rafaels88 has answered you may need to create a BC specific domain construct where some logical entity exists. For instance, a User in the Identity & Access Control BC would be an Author in one BC but perhaps a Supervisor in another.
You could also duplicate an AR in one BC as a VO in another. A Customer in the CRM BC may be the system of record for a customer and, therefore, contain a whole lot more information. In the Order BC, however, a Customer VO may only contain an Id, Name, and perhaps Address (for example).
So you will need to evaluate what type of object you have before deciding where to place it.

Creative Terminology

I seem to use bland words such as node, property, children (etc) too often, and I fear that someone else would have difficulty understanding my code simply because the parts' names are vague, common words.
How do you find creative names for classes and components to make them more memorable?
I am particularly having trouble with generic tools which have no real description except their rather generic functional purpose. I would like to know if others have found creative ways to name things rather than simply naming them by their utility, such as AnonymousFunctionWrapperCallerExecutorFactory.
It's hard to answer. I find them just because they seem to 'fit'.
What I do know, however, is that I find it basically impossible to move on writing code unless something is named correctly, and it 'feels' good. If it isn't named right, I find it hard to use, and the code is generally confusing.
I'm not too concerned about something being 'memorable', only 'accurate'.
I have been known to sit around thinking out loud about what to name something. Take your time, and make sure you are really happy with the name. don't be afraid of using common/simple words.
I don't really have an answer, but three things for you to think about.
The late Phil Karlton famously said: "There are only two hard problems in computer science. Cache Invalidation and Naming Things." So, the fact that you are having trouble coming up with good names is entirely normal and even expected.
OTOH, having trouble naming things can also be a sign of bad design. (And yes, I am perfectly aware, that #1 and #2 contradict each other. Or maybe one should think of it more like balancing each other.) E.g., if a thing has too many responsibilities, it is pretty much impossible to come up with a good name. (Witness all the "Service", "Util", "Model" and "Manager" classes in bad OO designs. Here's an example Google Code Search for "ManagerFactoryFactory".)
Also, your names should map to the domain jargon used by subject matter experts. If you can't find a subject matter expert, that's a sign that you are currently worrying about code that you're not supposed to worry about. (Basically, code that implements your core business domain should be implemented and designed well, code in ancillary domains should be implemented and designed so-so, and all other code should not be implemented or designed at all, but bought from a vendor, where what you are buying is their core business domain. [Please interpret "buy" and "vendor" liberally. Community-developed Free Software is just fine.])
Regarding #3 above, you mentioned in another comment that you are currently working on implementing a tree data structure. Unless your company is in the business of selling tree data structures, that is not a part of your core domain. And the reason that you have trouble finding good names could be that you are working outside your core domain. Now, "selling tree data structures" may sound stupid, but there are actually companies that do that. For example, the BCL team inside Microsoft's developer division: they actually sell (well, for certain definitions of "sell", anyway) the .NET framework's Base Class Libraries, which include, among others, tree data structures. But note that for example Microsoft's C++ compiler team actually (literally) buys their STL from a third-party vendor – they figure that their core domain is writing compilers, and they leave the writing of libraries to a company who considers writing STLs their core domain. (And indeed, AFAIK, that company does nothing but write and sell STL implementations. That's their sole product.)
If, however, selling tree data structures is your core domain, then the names you listed are just fine. They are the names that subject matter experts (programmers, in this case) use when talking about the domain of tree data structures.
Using 'metaphors' is a common theme in agile (and pattern) literature.
'Children' (in your question) is an example of a metaphor that is extensively used and for good reasons.
So, I'd encourage the use of metaphors, provided they are applicable and not a stretch of the imagination.
Metaphors are everywhere in computing. From files to bugs to pointers to streams... you can't avoid them.
I believe that for the purpose of standardization and communication, it's good to use a common vocab, like in the same case for design patterns. I have a problem with a programmer who keeps 'inventing' his own terms and I have trouble understanding him. (He kept using the term 'events orchestrating' instead of 'scripting' or 'FCFS process'. Kudos for creativity though!)
Those common vocab describe stuff we are used to. A node is a point, somewhere in a graph, in a tree, or what-not. One way is to be specific to the domain. If we are doing a mapping problem, instead of 'node', we can use 'location'. That helps in a sense, at least for me. So I find there is a need to balance being able to communicate with other programmers, and at the same time keeping the descriptor specific enough to help me remember what it does.
I think node, children, and property are great names. I can already guess the following about your classes, just by their "bland" names:
Node - this class is part of a graph of objects
children - this variable holds a list of nodes belonging to the containing node.
I don't think "node" is either vague or common, and if you're coding a generic data structure, it's probably ok to have generic names! (With that being said, if you are coding up a tree, you could use something like TreeNode to emphasize that the node is part of a tree.) One way you can make the life of developers who will use your API easier is to follow the naming conventions of your platform's built in libraries. If everyone calls a node a node, and an iterator an iterator, it makes life easy.
Names that reflect the purpose of the class, method or property are more memorable than creative ones. Modern IDEs make it easier to use longer names so feel fee to be descriptive. Getting creative won't help as much as getting accurate.
I recommend to pick nouns from a specific application domain. E.g. if you are putting cars in a tree, call the node class Car - the fact that it is also a node should be apparent from the API. Also, don't try to be too generic in your implementation - don't put all attributes of the car into a hashtable named properties, but create separate attributes for make, color, etc.
A lot of languages and coding styles like to use all sorts of descriptive prefixes. In PHP there are no clear types, so this may help greatly. Instead of doing
$isAvailable = true;
try
$bool_isAvailable = true;
It is admittedly a pain, but usually well worth the time.
I also like to use long names to describe things. It may seem strange, but is usually easier to remember, especially when I go back to refactor my code
$leftNode->properties < $leftTreeNode->arrayOfNodeProperties;
And if all else fails. Why not fall back on a solid star wars themed program.
$luke->lightsaber($darth[$ewoks]);
And lastly, in college I named my classes after my professor, and then my class methods all the things I wanted to do to that jerk.
$Kube->canEat($myShorts, $withKetchup);

How often do you need to create a real class hierarchy in your day to day programming?

I create business applications with heavy database use. Most of the programming work is just to connect components to the database and modifying components to adapt to general interface behaviour. I mostly use Delphi with its rich VCL library, and generally buy components needed. I keep most of the business logic in the database. I rarely get the chance to build a nice class hierarchy from the bottom up as there really is no need. Anyone else have this experience?
For me, occasionally a problem is clearer or easier with subclassing, but not often.
This also changes quite a bit in a given design as it's refactored.
My biggest problem is that programming courses and texts give so much weight to inheritance, hierarchies, and polymorphism through base classes (vs. interfaces or dynamic typing). This helps create legions of programmers that subclass everything and their mother.
The answer to this question is not totally language-agnostic;
Some languages like Java have a fairly limited set of language features available, meaning that subclassing is fairly often used because it's a convenient method for re-use, technical inheritance.
Closures and lambdas of C# make inheritance for technical reasons much less relevant. So normally inheritance is used for semantic reasons (like cat extends animal).
The last C# project I worked on, we more or less made all of the class hierarchies within a few weeks. After that it was more or less over.
On my current java project we create new class hierarchies all of the time.
Other languages will have other features that similarly affect this composition (mixins come to mind)
I put on my architecting/class design hat probably once or twice a month. It's probably the best hat I have and is the most fun to wear.
Depends what stage of the lifecycle your project is in though.
When your tackling problem domains you are well familiar with and already have a common code base to work from, you often have no need to create a new class hierarchy. It's when you stumble upon problems you have no ready solutions for, that you start building your own.
It's also very dependant on the type of applications you develop. If your domain already has well accepted conventions and libraries to work from, there probably isn't any need to reinvent the wheel (other than personal / academic interests). Some areas have inherently less available resources to work with, and in those you'll find yourself building everything from scratch most of the time.
A majority of applications, especially business applications, contains at least some kind of business logic in it. I would contend that business should not be in the database, but should rather be in the application. You can put referential integrity in the database as I think this is a good choice, but business logic should be only in the application.
By class hierarchy, I suppose you mean do you always have to end up with some inheritance in your object model, then the answer is no. But chances are you can often find some common code, factor it out and create a base class to contain the common code.
If you agree with me on the point that business logic should not be in the database, but should be in the application, then I recommend you look into the MVC Design Pattern to guide your design. You will find your design contain classes or objects. Your VCLs will represent your View, and you can have your Model classes map directly to the database table, i.e. each member in the class in the model corresponds to a field in a database table (again, this is the norm but there will be exception, where this simplicity fails to apply). Then you'll need a layer to handle the CRUD (Create, Read, Update, Delete) of the Model classes to the database tables. You will end up with an "layered" application that is easier to maintain and enhance.
It depends on what you mean by hierarchy - inheritance or layering?
When object oriented languages first came out, inheritance was overused. Complicated hierarchies were common. Now, interfaces (as in Java and C#) provide a simpler way to get the benefit of polymorphism without the complications of inheritance. I rarely use inheritance anymore.
Layering, however, is vital when creating a large application. Layering prevents general low-level classes (like lists) from directly referencing specific high-level classes (like web browser windows). As far as I know, there isn't a formal way to describe layering, but there are general guidelines (model-view-controller (MVC), separate GUI logic from business logic, separate data from presentation, etc.).
It really depends on the types/phases of the projects you're working on. I happen to do that everyday because I'm working on database internals for a new database, creating related libraries/frameworks. I'd imagine doing that a lot less if I'm working within a mature framework using other people's libraries.
I'm doing Infrastructure for our companys' product, so I'm writing a lot of code that will be used later by guys in other teams. So I end up writing lots of abstract classes, interfaces, hierarchies and so on. Mostly it's just a pattern of "default behaviour in an abstract/virtual class, which other programmers may override".
Very challenging, I must say.
The time that I find class hierarchies most beneficial is when the relationship between objects actually does match a true "is-a" relationship in the domain.
However if I can avoid large hierarchies I will due to the fact that they are often a little more tricky to map to relational databases and can really complicate your database designs. Since you say most of your applications make heavy use of databases this would be something to take into consideration.

How to avoid Anemic Domain Models and maintain Separation of Concerns?

It seems that the decision to make your objects fully cognizant of their roles within the system, and still avoid having too many dependencies within the domain model on the database, and service layers?
For example: Say that I've got an entity with a revision history, and several "lookup tables" that the data references, your entity object should have methods to get the details from some of the lookup tables, whether by providing access to the lookup table rows, or by delegating methods down to them, but in order to do so it depends on the database layer to read the data from those rows. Also, when the entity is saved, It needs to know not only how to save itself, but also to save entries into the revision history. Is it necessary to pass references to dozens of different data layer objects and service objects to the model object? This seems like it makes the logic far more complex to understand than just passing back and forth thin models to service layer objects, but I've heard many "wise men" recommending this sort of structure.
Really really good question. I have spent quite a bit of time thinking about such topics.
You demonstrate great insight by noting the tension between an expressive domain model and separation of concerns. This is much like the tension in the question I asked about Tell Don't Ask and Single Responsibility Principle.
Here is my view on the topic.
A domain model is anemic because it contains no domain logic. Other objects get and set data using an anemic domain object. What you describe doesn't sound like domain logic to me. It might be, but generally, look-up tables and other technical language is most likely terms that mean something to us but not necessarily anything to the customers. If this is incorrect, please clarify.
Anyway, the construction and persistence of domain objects shouldn't be contained in the domain objects themselves because that isn't domain logic.
So to answer the question, no, you shouldn't inject a whole bunch of non-domain objects/concepts like lookup tables and other infrastructure details. This is a leak of one concern into another. The Factory and Repository patterns from Domain-Driven Design are best suited to keep these concerns apart from the domain model itself.
But note that if you don't have any domain logic, then you will end up with anemic domain objects, i.e. bags of brainless getters and setters, which is how some shops claim to do SOA / service layers.
So how do you get the best of both worlds? How do you focus your domain objects only domain logic, while keeping UI, construction, persistence, etc. out of the way? I recommend you use a technique like Double Dispatch, or some form of restricted method access.
Here's an example of Double Dispatch. Say you have this line of code:
entity.saveIn(repository);
In your question, saveIn() would have all sorts of knowledge about the data layer. Using Double Dispatch, saveIn() does this:
repository.saveEntity(this.foo, this.bar, this.baz);
And the saveEntity() method of the repository has all of the knowledge of how to save in the data layer, as it should.
In addition to this setup, you could have:
repository.save(entity);
which just calls
entity.saveIn(this);
I re-read this and I notice that the entity is still thin because it is simply dispatching its persistence to the repository. But in this case, the entity is supposed to be thin because you didn't describe any other domain logic. In this situation, you could say "screw Double Dispatch, give me accessors."
And yeah, you could, but IMO it exposes too much of how your entity is implemented, and those accessors are distractions from domain logic. I think the only class that should have gets and sets is a class whose name ends in "Accessor".
I'll wrap this up soon. Personally, I don't write my entities with saveIn() methods, because I think even just having a saveIn() method tends to litter the domain object with distractions. I use either the friend class pattern, package-private access, or possibly the Builder pattern.
OK, I'm done. As I said, I've obsessed on this topic quite a bit.
"thin models to service layer objects" is what you do when you really want to write the service layer.
ORM is what you do when you don't want to write the service layer.
When you work with an ORM, you are still aware of the fact that navigation may involve a query, but you don't dwell on it.
Lookup tables can be a relational crutch that gets used when there isn't a very complete object model. Instead of things referencing things, you have codes, which must be looked up. In many cases, the codes devolve to little more than a static pool of strings with database keys. And the relevant methods wind up in odd places in the software.
However, if there is a more complete object model, we have first-class things instead of these degenerate lookup values.
For example, I've got some business transactions which have one of n different "rate plans" -- a kind of pricing model. Right now, the legacy relational database has the rate plan as a lookup table with a code, some pricing numbers, and (sometimes) a description.
[Everyone knows the codes -- the codes are sacred. No one is sure what the proper descriptions should be. But they know the codes.]
But really, a "rate plan" is an object that is associated with a contract; the rate plan has the method that computes the final price. When an app asks the contract for a price, the contract delegates some of the pricing work to the associated rate plan object.
There may have been some database query going on to lookup the rate plan when producing a contract price, but that's incidental to the delegation of responsibility between the two classes.
I aggree with DeadBeef - therein lies the tension. I don't really see though how a domain model is 'anemic' simply because it doesn't save itself.
There has to be much more to it. ie. It's anemic because the service is doing all the business rules and not the domain entity.
Service(IRepository) injected
Save(){
DomainEntity.DoSomething();
Repository.Save(DomainEntity);
}
'Do Something' is the business logic of the domain entity.
**This would be anemic**:
Service(IRepository) injected
Save(){
if(DomainEntity.IsSomething)
DomainEntity.SetItProperty();
Repository.Save(DomainEntity);
}
See the inherit difference ? I do :)
Try the "repository pattern" and "Domain driven design". DDD suggests to define certain entities as Aggregate-roots of other objects. Each Aggregate is encapsulated. The entities are "persistence ignorant". All the persistence-related code is put in a repository object which manages Data-access for the entity. This way you don't have to mix persistence-related code with your business logic. If you are interested in DDD, check out eric evans book.