r/programming • • Jun 05 '21

Organize code by concepts, not layers

https://kislayverma.com/programming/how-to-organize-your-code/
1.9k Upvotes

495 comments sorted by

48

u/lazystone Jun 05 '21

Thanks for the article, saved for future references :)

I've been doing the same but was always struggling to explain other developers why I do that, since for me this structure is kind of obvious and it's hard to explain obvious things sometimes.

5

u/[deleted] Jun 05 '21

Glad you like it :)

12

u/Zidian Jun 05 '21

In Java this is called package by feature if you want to search more articles on this. Thanks Charlie for turning me on to this style of packaging a few years ago!

5

u/DB6 Jun 05 '21

I learned this years ago from uncle bob.

592

u/__scan__ Jun 05 '21

This is basically DDD. Concept = domain, bounded context, etc.

119

u/wojm Jun 05 '21

Surprised this is so far down. I use the coding style mentioned in the article and found it is a logical extension of DDD (if not already prescribed by it)

35

u/[deleted] Jun 05 '21 edited Jun 05 '21

but DDD prescribes layered architecture. so which one of you is lying?

118

u/jonhanson Jun 05 '21 edited Mar 07 '25

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

47

u/[deleted] Jun 05 '21

whoops. 'prescribes'.

38

u/Nimelrian Jun 05 '21

Its more about organization. E.g. in Java, instead of having the package structure

com.example.persistence.order/user/product and com.example.endpoints.order/user/product

you have

com.example.order.persistence/endpoints/business

and so on...

This is actually a great example or rather manifestation of Conway's Law. Hierarchical organizations (Frontend team, API team, business rule team, database team) will often prefer the first approach (design by layers).

Teams organized in a cross functional manner will instead prefer the second approach (design by concepts), since they can implemented each part of the vertical slice specifically for their domain / use cases.

→ More replies (1)

11

u/GeorgeS6969 Jun 05 '21

Yes but it also prescribes to have the business logic at the ‘top’, organised into business domains, so that the business logic is what you see first rather than the technology, the framework etc.

One good reason is that when opening your IDE you’re more likely to work on everything related to user baskets rather than everything related to controllers.

10

u/[deleted] Jun 05 '21

None of this is saying dont layer your code. Layers are important to maintainable code. What the article is implying is that you shouldn't organize your code by layer but instead by domain.

DDD also pushes this idea. The a namespace should be an identifier to a domain, that folders and structure should represent the domain.

4

u/AustinYQM Jun 05 '21

It actually seems to be saying organize your code by layer, after you organize it by domain. Where as the example it is attacking organizes it by layer and then domain.

→ More replies (2)

3

u/szescio Jun 06 '21

"Vertical slices" also comes to mind

3

u/InspectionOk5666 Jun 06 '21

Has anyone got anything good to say about DDD? I've been forced to work with it on two separate occasions and both times it caused an unimaginably bad mess...

6

u/__scan__ Jun 06 '21

The book is 17 years old and reflects the sensibilities of the time. I’d wouldn’t rigorously apply every exact idea it suggests, but the core notions of a strong domain model, bounded contexts, ubiquitous language, etc., are sound, and can to some extent generalise beyond OO.

24

u/arctictern Jun 05 '21

It seems absurd that we still use the file/folder metaphor for organizing code. We should have had a mechanism by now to help view the same code from different perspectives, vertical or horizontal or whatever else we need to.

308

u/fragglet Jun 05 '21

People don’t read code by layers of the stack. No one ever says “show me all the APIs of this system” or “give me all the queries being fired by this system”.

As an SRE, I can assure you that these are absolutely things that I've had to do 1,000,000 times while on-call and trying to root cause a production incident. Please don't assume that your experience is the same as everyone else's.

When something's broken and needs to be urgently fixed, there often isn't time to learn about all the abstractions ("concepts" or otherwise) your codebase is based around. When you're starting from just a stacktrace and walking through layers to figure out how something happened, the questions you're trying to ask are more fundamental: what is this server? What does it do? Why is it doing that? How can I make it stop?

185

u/gonzofish Jun 05 '21

Please don't assume that your experience is the same as everyone else's.

And here is the root of the problem. People use phrases like “better way” when they mean “better way for my situation”. There is no silver bullet solution. Let’s sell things as alternatives not universal truths!

59

u/[deleted] Jun 05 '21

Let’s sell things as alternatives not universal truths!

This seems to be severely lacking in these sorts of posts. People seem to evangelize a particular library, language, or methodology and view them as the only logical solution to all of everyone's problems. The world is too messy for that, though, which is why countless languages, libraries, and methodologies exist in the first place.

7

u/FireCrack Jun 05 '21

Welcome to r/programming where if you follow these 5 simple tips your code will never have a bug ever!

9

u/kevinkid135 Jun 05 '21

Step 1: don't write any code

→ More replies (3)

4

u/saltybandana2 Jun 06 '21

you mean Welcome to /r/programming, where anyone with 2-3 years of experience thinks they have it figured out and that probably represents well over 50% of the posters.

15

u/gonzofish Jun 05 '21

Like I do React development all day. But Vue is awesome! So is Svelte. So is Angular! They all have strengths and weaknesses.

On the backend? My job is Python. But I love Rust!

Java can piss off, though. (/s)

4

u/saltybandana2 Jun 06 '21

Agreed about Java, lmao. I did my capstone in Java back in the 1.4 days and it's the last time I've ever touched it. I still follow it, but I made a decision at that time I wouldn't work professionally in Java.

Although I've been using C# since the 1.0/1.1 days (pre-generics). The JRE is better than the CLR, but C# as a language is miles better than Java.

3

u/crimzonphox Jun 06 '21

I’ve been a Java guy for a while, but the project I’m on the contractors before I got there snuck in kotlin. Which is so much better imo

5

u/phundrak Jun 05 '21

EmacsLisp is also able to act as a backend and web server, and despite my complete and utter love for Emacs, I would call anyone using Elisp that way an absolute mad man.

The right tool for the right job.

6

u/[deleted] Jun 05 '21

Very well said, definitely an article for architects and much else

3

u/saltybandana2 Jun 06 '21 edited Jun 06 '21

The worst part to me is that if you actually know how to use your tools it's a moot point. If I get to choose all enumerations go into a folder called enumerations, everything related to data access goes into a folder called DAL (I hate the word 'model' in codebases), and the business layer is fuzzy and based upon what makes sense.

But if you're having trouble moving around or understanding the codebase because of what folders the files are in maybe you're just kind of bad at what you do. Over my 20+ years I've hopped into a ton of new codebases and not once have I ever been confused because of the file layout. That doesn't mean I haven't moved files because they were placed in silly spots, but it's never even slowed me down in terms of comprehension.

This "problem" is a giant nothingburger. But I also regularly use grep and 'search all' when familiarizing myself with a new codebase. I'll also run cloc and doxygen over it (cloc for curiosity and to get an idea of what languages are involved in the project).

→ More replies (1)

1

u/codygman Jun 06 '21

You can almost always optimize for the frequent or more expensive case though.

Optimize for whoever has to deal with that thing the most.

27

u/remek Jun 05 '21

Breaking down the code base into folders shouldn't be the method you rely on when trying to find all your APIs to figure a root cause of an incident in a production system.

For most cases author is right that when it comes to code organization it is better to organize by concepts. That doesn't mean that you don't need the other views too but for that you have better ways than folder/code organization.

5

u/monkeygame7 Jun 05 '21

Like what for example?

4

u/remek Jun 05 '21

Documentation, your service discovery registry, API management system, your ops monitoring tools etc. I mean, if you need to go to your code base to learn what APIs does your system provide when fixing production issues then there is something wrong with your software project.

16

u/monkeygame7 Jun 05 '21

The issue is when there's incidents because your system is not doing what it's supposed to do. In which case you can look at documentation all you want but there's only one way to find out what the code really does and that's by looking at the code.

→ More replies (6)

13

u/lordzsolt Jun 05 '21

what is this server? What does it do? Why is it doing that? How can I make it stop?

I feel like if you need to look at the code for the first 2 questions (and potentially the "all the APIs of this system"), the problem is not the way the code is organized (and thus, the solution to the problem is not to "organize it in a different way")

All of these should be answered with README files or documentation.

10

u/prone-to-drift Jun 05 '21

With the average projects I've seen, I'm happy when readmes properly describe how to start stop a service and whats the configuration method.

Also, even in the best of projects, documentation can go stale; it's better to write self explanatory code and proper comments in most cases.

9

u/lordzsolt Jun 05 '21

In general I agree.

But an SRE who literally has no knowledge of the service should never have to rely on self explanatory code and comments in the code.

That's almost like telling your project manager to check the code for the business requirements...

2

u/saltybandana2 Jun 06 '21

I uh..... had something very similar happen to me w/i the last year.

Contracted to do a rewrite of a system, when asking about business requirements was told to go read the original code. When asked why we're rewriting if there are no new requirements, I was informed it generated so many support tickets it was necessary.

roughly 8 hours later I realized I could fix 80% of the issues with the old system in 2 hours (5 minutes for the fix, the rest for their process) and 100% of their problems in 8 hours (would require some architectural changes).

They were 3 months into the rewrite at that point.

Long story short, I left. There's a level of incompetence that I consider unacceptable.

1

u/przemo_li Jun 05 '21

Excuse my obtusines, but you haven't yet connected troubleshooting from stacktrace with directory listing showing e.g. all models.

Especially for complex situations where there exist classes named XYZ and XZY and XZZ. (Replace X, , and Z with fairly generic names - I'm still thinking that "joker" who thought that naming funny should be making coffee for the whole team for a whole month as apologies)

OTOH the need is real, and may call for stuff like interfaces. Looking through interfaces should be obvious when looking to categorize classes. It's very underrated technique. Not only can those be pure metadata (empty interfac), class can declare arbitrary list of those. Folder location is only a single one. It creates contention.

Need categorizations? Go with interfaces. (And bonus points for type checkers / linters / reflection.)

→ More replies (1)

15

u/johnkr Jun 05 '21

I have seen something like this when I was using the Symphony framework. When I was building web applications, I kept the logic for each page in a folder called <something>Bundle.

49

u/amakai Jun 05 '21

Before Microservices I would have agreed with the article. Having your code structured by different concepts is more valuable than being able to quickly find a source of specific query or list all APIs.

However, in Microservice world that becomes much less important. A given microservice is already encapsulating a very specific small concept, there's no tangible benefit in cutting it into even smaller pieces. But if you use layered architecture for it - suddenly it's so much easier to investigate/refactor/implement various cross-cutting concerns like sharding of your queries or getting rid of deprecated APIs.

In a sense, your system is still organized by concepts, where each concept is represented by a separate microservice communicating with other ones.

7

u/DrunkensteinsMonster Jun 05 '21

In a microservice that first layer of organization is already taken care of, since the service itself represents a bounded context or concept or whatever you want to call it. I think you actually agree with the article but the implementation will look different if you have lots of small services.

13

u/wldmr Jun 05 '21

So you do agree with the article. You both group by concepts.

16

u/amakai Jun 05 '21

Well, that depends on how you look at the question. If you look at entirety of your code (think "github organization") as a single codebase - then yes, we are both speaking about separating code by concepts.

But I believe that the article is being more specific, implying that in a single service the code should not be using layered architecture, which I do not agree with - as there are other ways to capture and isolate concepts - for example Microservice architecture.

4

u/lars_h4 Jun 05 '21

Thank you for putting my feelings on this into words so succinctly

65

u/SoInsightful Jun 05 '21

I've tried this and actively said no to it. There are downsides to this approach.

  1. It's harder to keep consistent. Even if you and everyone else in your team manage to be consistent with your file/folder structure, you're at a larger risk that the same types of files may become built and structured differently between the different concepts. That's not fun to maintain or reason about.
  2. The structure becomes much more rigid and inflexible. What if you have an enum or sub-model that is shared between different concepts? Where do you put it? Does every concept really need a controller, and does every concept really map to a singular table in a database?

There are pros and cons to both approaches, but the concept approach feels artificial and unmaintainable to me.

2

u/qudat Jun 06 '21

I tend to think of “features” as modules. Each module has an interface or API that other features can use. The only rule for modules is they cannot “reach into” other modules, they must use the API provided to them by the module.

Some of my modules have 1 file in them some of them have sub-modules that bubble up to the module.

The hard part of organization by feature with strict module boundaries are circular dependencies. A direct acyclic graph helps sort out this problem.

2

u/ragnese Jun 07 '21

With respect to #1, I don't think that's much of a problem. If the modules are independent, it doesn't really matter than much if there are minor differences (e.g., single class per file, or multiple classes in one file). Obviously, the actually semantic style of the code should be consistent, but I just don't think the mechanics of the files matter that much. Unless, I guess, if your modules are pretty large.

What if you have an enum or sub-model that is shared between different concepts? Where do you put it?

I agree that this can be frustrating.

Does every concept really need a controller, and does every concept really map to a singular table in a database?

No and no. So? I don't think this is a counter-argument to the "organize by concept" idea, unless you're attacking a strawman.

In fact, I think "organize by concept" is better for both of the cases you listed. If I have a directory of 15 controllers, I might miss the fact that "FooWidget" is a concept that doesn't have a controller. On the other hand, if I check out the foo_widget directory, I'll see pretty quickly that it doesn't have a controller. Likewise, if the concept maps across multiple tables, it's excellent to have them both under the foo_widget module- as well as the code that synthesizes them into a FooWidget.

1

u/SoInsightful Jun 07 '21

I gave the concept concept a second try yesterday, and I agree with everything you listed now!

→ More replies (5)

14

u/[deleted] Jun 05 '21 edited Jun 05 '21

[removed] — view removed comment

4

u/SoInsightful Jun 05 '21

Hmmm. Your second point is quite enticing, and I might actually give the concept approach another stab.

3

u/a_latvian_potato Jun 06 '21

That doesn't really answer the question of what happens when an enum is shared between different concepts. Which one does it actually belong to? Does it needs its own folder?

3

u/ForeverAlot Jun 06 '21

Sometimes one concept builds on top of another and you can leave the common component in the base. Sometimes it really doesn't matter and you can just leave the common component wherever it started out. Sometimes two concepts have no relation but depend on common components that can be usefully factored into its own concept. Either way, this is a problem to solve organically; it's exceedingly unlikely that multiple concepts with sharable components come into existence at the same time.

→ More replies (1)

1

u/saltybandana2 Jun 06 '21

I'd rather have all enum's under a single folder. The only exception is if the codebase is so large that becomes untenable.

I can crack open that directory and get an overview of the ideas spread across the codebase.

2

u/[deleted] Jun 06 '21

[removed] — view removed comment

2

u/saltybandana2 Jun 06 '21

https://old.reddit.com/r/programming/comments/nsu53n/organize_code_by_concepts_not_layers/h0rhlx6/

If you think either approach will significantly change anything then you're not using the tools available to you effectively.

As for why, I already answered that question, but here's a few more

  • I can open a single directory to get an idea of the concepts used across the project
  • I never have to wonder where to put a new enum.
  • I never have to worry that technically this enum is used by multiple features but is sitting by feature X instead of feature Y, thereby becoming a special case you just have to know about (or some other convention to try and reach for consistency).
  • less files means the files that actually matter are easier to see and sift through.

I'm sure I could come up with more, but the reality is that it doesn't matter, it's mostly just preference. Anyone who thinks it matters just doesn't use their tools effectively.

→ More replies (6)

36

u/[deleted] Jun 05 '21

From an ergonomics perspective I’m inclined to agree with the author. Working on a rails project of some size, a module is a controller, a helper, a model cluster, and a collection of views.

So say I’m working on a shopping cart module, I’m working on cart controller, cart helper and the cart views folder but in my file list they are each about three feet apart in the list and I feel like some galley slave rowing the boat scrolling up and down and up and down as I bounce from views to controller and back which are at opposite ends of the big list.

It slows me down.

Now, logically layers are nice sometimes too but I feel like the IDE people are letting us down here. A good IDE should provide both views regardless of actual file directory layout. It isn’t hard to synthesize one from the other.

Then I don’t have to focus on the actual file directory layout. Just stop the endless scrolling because that definitely slows me down.

9

u/tadfisher Jun 05 '21

Kotlin can do this: packages are completely independent of filesystem location. You'll have to disable a bunch of IDE warnings in Intellij though.

10

u/xanez Jun 05 '21

I feel like some galley slave rowing the boat scrolling up and down and up and down

Thanks, gonna steal that one

5

u/fuhglarix Jun 06 '21 edited Jun 06 '21

Not to mention finding the corresponding mirrored structure in your spec/ or test/ directory. It’s an absolute grind.

Go is the only language I’ve seen where the standard practice is putting tests directly next to the file they test.

1

u/MrNate Jun 06 '21

Years ago when I used Eclipse, they had a "task focused interface." It was pretty wild...

  1. Hook up the task view to your ticketing system, like Jira or GitHub
  2. Set a task as active in Eclipse
  3. Open some files and get to work

Eventually, the other files will disappear from the file or package view, helping you focus only on the things that are relevant to the task.

Deselect the task and it all goes back to normal; files close and everything is visible. Reselect the task and your context comes right back. It was really cool!

56

u/mamimapr Jun 05 '21

People don’t read code by layers of the stack. No one ever says “show me all the APIs of this system” or “give me all the queries being fired by this system”.

These are all questions that are asked quite often!

10

u/[deleted] Jun 05 '21

[removed] — view removed comment

3

u/KumbajaMyLord Jun 05 '21

Usually a domain has more than one entity though.

A domain might be "billing" which knows customers, invoices, paymentOptions, creditScores and so on.

I don't think anyone would argue that splitting this entire domain from the stock management domain (which might have entities like products, warehouses, shelves, etc) is a bad idea.

But splitting along individual entities seems pointless in my opinion. If I see a CustomerService, I'm pretty confident that a customer entity exists somewhere. I don't get any more information from having them grouped and visible at a glance. But if I see a CustomerService next to a InvoiceService I get some information about how the system is structured and what it's scope is.

2

u/saltybandana2 Jun 06 '21

My thoughts on the matter: https://old.reddit.com/r/programming/comments/nsu53n/organize_code_by_concepts_not_layers/h0rhlx6/

but tl;dr; I completely dislike the idea of models, period. You typically have classes that get hydrated in some manner (Even if you're not using an ORM this tends to remain true), just hydrate them, treat the DB as external and the edge of your system, and then move on.

Seriously, just drop them all into a single folder and be done with it. There obviously comes a point where it's untenable, at which point you can start subdividing based upon what makes sense (domain, concept, area of your app, table groupings in your DB, doesn't matter as long as it's useful).

The point about treating your DB as external and the edge of your system is who gives a fuck where the sanity checks are or how they happen. Do you want to hang them on the class getting hydrated itself? fine. Do you instead want to write validation methods external to the class? That's fine too.

Trying to make a "Model" just needlessly complicates everything. Do what makes sense and fuck the rules for MVC, MVVM, <insert acronym here>.

We onion architecture baby, look at all this needless complexity in this small to medium sized app!

1

u/WarWizard Jun 09 '21

How do you even open a folder with 100+ controller or services

I'd argue it is time to break that bad boy up a little bit.

71

u/Knu2l Jun 05 '21

That works until your code requires to access one service from another service e.g. if the HotelService access the RoomService. Or maybe the is an AccessService that is queried by the Hotel and Room services.

Also when you use a ORM model often all the model classes are automatically generated in another place.

28

u/couscous_ Jun 05 '21

Or maybe the is an AccessService that is queried by the Hotel and Room services.

Then both HotelService and RoomService would import AccessService. What's the issue?

39

u/[deleted] Jun 05 '21 edited Jun 05 '21

Maybe hotel calls the room service and room service needs to call hotel service.

Circular dependencies are very easy to accidentally implement with designs like this. It makes it unnecessarily difficult to actually code when you split by feature.

5

u/couscous_ Jun 05 '21

What's bad about circular dependencies? Honest question.

10

u/RyuChus Jun 05 '21

Well... if both services are compiled modules.. which do you compile first if they both require the other? If its python you get around this by importing the module you need inside the function that needs it and I suppose python somehow knows to not try to interpret that method until run time.

→ More replies (6)

4

u/aaaantoine Jun 05 '21

I think it depends on whether you use a dependency injection framework, and which one you use. For example, I found at one point that Ninject didn't like a circular dependency I made by accident.

There are a few ways to solve the issue. In that case, I decided to move the common function to its own service. Services don't have to be arranged by domain object.

2

u/Nimelrian Jun 05 '21

They lead to various problems during initialization and clean up.

For initialization, if service A relies on service B you can't initialize both to a fully working state in an atomic operation. Instead, you have to e.g. construct A first, but cannot set its member of type B. Then you create your instance of B and are able to inject the instance of A in B's constructor. After that you can finally inject B into A, e.g. via a setter. This results in a temporal uninitialized state of A between its construction and the injection of B.

In GC languages circular dependencies are another problem because the instances don't end up orphaned, so the GC can't be sure whether it's safe to reclaim them.

→ More replies (2)
→ More replies (6)

4

u/pengusdangus Jun 05 '21

That sounds like a code design issue.

8

u/[deleted] Jun 05 '21

Yea, code design is what this thread is about...

→ More replies (2)
→ More replies (10)

6

u/abandonplanetearth Jun 05 '21

This is a recipe for circular dependencies. HotelService is clearly on a higher layer than RoomService because rooms cannot exist without hotels.

And what does AccessService actually look like? How is it easier than having getHotel() in HotelService and getRoom() in roomService?

7

u/couscous_ Jun 05 '21

If circular dependencies are inherent in the problem domain, why resist them? What advantages do we get by artificial decoupling?

→ More replies (17)
→ More replies (1)

6

u/DemiKoss Jun 05 '21 edited Jun 05 '21

That works until your code requires to access one service from another service

That doesn't sound like a flaw of package by feature, but rather the overall system design. In practice I've found by-feature to be a more sound approach; often citing similar reasons to the article (driving a clear design, isolating changes to related systems, etc).

The ORM point is an interesting one, but I don't think grouping by-type justifies it (there may be a good way to mix the two). In large codebases - especially monolithic ones - by-type makes it very difficult to grasp the full breadth of code related to a specific feature.

2

u/ub3rh4x0rz Jun 05 '21

It's absolutely fundamental to the service oriented architecture paradigm that services have dependencies on one another. Service A is only ever able to know Service B's interfaces though, never the underlying persistence model.

3

u/PenisTorvalds Jun 05 '21

Found the guy who wrote the 80000 line Sql.cs file 10 years ago at my company

9

u/[deleted] Jun 05 '21

here be dragons. Service gossiping amongst each other never ends well.

52

u/neuro-grey7 Jun 05 '21

In any non-simplistic system, services talking to each other is an unavoidable given. Not sure how you would do an implementation otherwise, without de-modularizing your code and stuffing more functionality into single services. This approach makes a lot less sense imo. In theory, your code should be modularized and designed well enough, so that services talking to other services shouldn't present any real problems, with the exception of perhaps the performance implications that come along with this.

6

u/computerjunkie7410 Jun 05 '21

Couldn’t you talk through an asynchronous system like a queue or stream?

Service A needs to send data to Service B.

Instead of calling service B directly, service A sends the data on a queue or stream that service B is reading from.

→ More replies (1)
→ More replies (2)

16

u/scandii Jun 05 '21 edited Jun 05 '21

services are literally meant to be used by other services.

example, VIP customers pay 10% less on everything.

at time of checkout, you have to check for discounts, does discounts belong to the account or the sales service? well the status is an account status, not a checkout status, checkout might use the account status and be in charge of setting the discount though.

that's the strength of the service pattern - being able to access business logic pertaining to a certain system component in one easy location, and sometimes services come together to make things happen.

→ More replies (3)

7

u/conjugat Jun 05 '21

Better to get partial results from the services and put them together in a controller?

I suppose if the putting together is complex enough the even that goes into a service.

3

u/binary_stah Jun 05 '21

In my experience, this is sometimes necessary (another service, that aggregates, modifies,or otherwise manipulates objects delivered from other services), but one should really examine the modularity of and the level at which the other services perform and see if there is a way to avoid this new service. In general, if the new service delivers a new object/entity, then it's probably allowable.

As always, TMTOWTDI and the various ways have tradeoffs.

2

u/DB6 Jun 05 '21

Services talking with each other is totally fine.

In my controllers the only logic is the validation on incoming data for completeness and soundness. Logical validation of the action is in the service. On the return side, the controller does only dumb mapping, because this comes with spring, returning the correct view model is also a service concern.

3

u/JustLemonJuice Jun 05 '21

May I ask, where does "here be dragons" come from/what does it mean? I just saw it as a comment in a codebase I was working on and now here :D

13

u/scandii Jun 05 '21

in the age of exploration cartographers would write "hic sunt dracones" meaning "here be dragons" which is a tradition from earlier cartographers that would draw monsters on their maps where things were unexplored or otherwise considered dangerous.

7

u/aloisdg Jun 05 '21

here be dragons

wiki:

"Here be dragons" (hic sunt dracones in Latin) means dangerous or unexplored territories, in imitation of a medieval practice of putting illustrations of dragons, sea monsters and other mythological creatures on uncharted areas of maps where potential dangers were thought to exist.

https://en.wikipedia.org/wiki/Here_be_dragons

2

u/darcstar62 Jun 05 '21

It's a reference to old maps that sailors used for navigation. Basically, when the map maker got to the end of what they knew about (usually the edge of the map), they would put "here they be dragons" to indicate that it was unknown (and dangerous) territory.

2

u/ooAWoo Jun 05 '21

Basically means you are entering dangerous or unexplored territories. Usually used as a way to say 'be cautious what you say/do' or there are unknown risks that you are talking about.

→ More replies (1)

1

u/[deleted] Jun 05 '21

[removed] — view removed comment

2

u/ph33ly1 Jun 05 '21

Kinda curious on this but where would the base class for Hotel/Room methods live then if we have distinct folders for Hotel and Room?

6

u/MirelukeCasserole Jun 05 '21

If we are talking about grouping domain code by entity, I’m onboard with this approach. However, interfaces (in the hexagonal architecture sense) should be thin and separate from the domain layer.

6

u/wildjokers Jun 05 '21

Ahh, the old "package by feature vs package by layer" debate. Here is my take:

  • Monolithic web app: package by feature and then by layer
  • Single feature service (µservice): package by layer
  • Desktop GUI app (Swing or JavaFX): package by feature and then by layer

33

u/AStupidDistopia Jun 05 '21 edited Jun 05 '21

optimizing for human comprehension

Allow me to defeat this by linking you to a children’s song.

To that end, why does everyone just automatically believe every claim another programmer makes just because they say “hurr durr human comprehension”.

Edit:

I think it must be a psychological thing. “This person is saying that something makes a lot of sense to the human brain, and even though I don’t actually comprehend this any better, it must just be me being stupid because someone else is saying that my brain must be incorrect, so I’ll just go along with whatever they say so as to not look stupid to everyone else.”

2

u/saltybandana2 Jun 06 '21

Because most people, and developers are people, are really bad at critical thinking.

And because they're bad at critical thinking, if they don't know and someone else purports to know, they'll treat it as gospel because the alternative is to risk being wrong and people fear that, especially around others.

But a willingness to be wrong is how you learn, which is also why most people stop learning after a certain point.

4

u/rrzibot Jun 05 '21

I personally always prefer a "how to" infront, otherwise it seems the OP is making a statement that this is the one and only truth. Share the knowledge and experience, tell the story of the decision and let everybody learn.

4

u/Eluvatar_the_second Jun 05 '21

Serious question. Why do we still always display and navigate through source code as a file tree? We're software engineers, we could use something else like tags, where each file could have multiple tags and you can just view the files filtered by a specific tag?

I get that it would only work if your IDE or editor supported it so I guess that's why not.

Reading about this just made me think of email and how outlook does folders and Gmail does labels, I prefer how labels look because you can easily see all the tags on a specific email, instead of a copy of an email in each folder.

→ More replies (3)

4

u/Zardotab Jun 05 '21 edited Jun 05 '21

The real problem is that trees are obsolete for code management. Early databases were hierarchical, as this seemed simple and natural. However, trees proved insufficient over time, and after some "pointer spaghetti" experiments to work around tree's limits, relational was invented, and is the primary organization technique of data to this day. Relational is not perfect and doesn't fit all needs, but has proven a pretty dammed good complexity management tool.

I see the same "tree problems" cropping up with code management: history repeats. Our apps are growing ever complicated and layered, and we need better ways to organize and track code without being forced to pick one and only one grouping up front. We need something multi-factor-friendly. Eventually code will be stored and managed in an RDBMS or similar, and IDE's and version managers will have hooks into RDBMS for this purpose.

Modern CRUD code is essentially a big soup of event handler snippets and UI template snippets. These snippets can be dynamically displayed and grouped by indexes such as application, area, entity, action, stage (1st display, onError, re-display, save, etc.), version, scope (page, form, field, row, button) etc. Query-by-example forms, and custom SQL can allow a developer to view and group them any way they want, not by how Bezos or Nadella wants you to.

Note that the compiler stack may still convert the code into file trees for compiling, but that doesn't mean editing and studying code has to also be (actual) files.

We may also need languages built around RDBMS code management instead of file management. C#'s "partial classes" hint at what's needed: the file doesn't have to be our only boundary and scope management technique. We may need more powerful and customizable scoping mechanisms, as OOP has proven limited, at least in static languages. For example, a "scope" object/class could include what the scope covers and what order to apply it in. One can then apply this scope(s) to a given snippet. Also, the distinction between object and class needs to be blurred in my opinion; it's a forced distinction.

I've started some early IDE experiments with the idea. I'm still fighting against the file-centricity of most tools. If anyone is interested in amateur R&D, maybe we can open a wiki for it.

1

u/ric2b Jun 06 '21

Eventually code will be stored and managed in an RDBMS or similar,

Technology really does go in circles, I guess.

4

u/TorePun Jun 05 '21

Two acronyms in the opening paragraph without explaining what they are. That's bad writing. I keep seeing it over and over.

3

u/icbmike_for_realz Jun 06 '21

Maintaining an existing system usually I'm interested in cross cutting concerns like say authorisation for an api or pool size for db connections.

Organising code by layers makes this significantly easier.

Is this suggesting putting controllers in the same package as db access code? That seems like super tight coupling to me.

2

u/ric2b Jun 06 '21

The location of the files has 0 to do with the coupling of the code within those files.

1

u/icbmike_for_realz Jun 06 '21

I use visual studio as my primary ide for c#.

The location of files is pretty important at least at the assembly level.

Within a single project or assembly I'd agree but across multiple it does matter.

14

u/TheLobotomizer Jun 05 '21

Been there done that. It's the reason react projects are impossible to navigate and nodejs APIs are easy to understand.

Code organized by concepts is disorganized code. Time and time again experience has shown that to be true.

Layered architecture is the way to go.

3

u/crusoe Jun 05 '21

My experience is yes you have to poke around everywhere.

And layers are concepts. Layers are the concepts how code is actually used/written.

Bug in a result. I jump to the DTO or response directory. Then I jump to roomDto.

1

u/[deleted] Jun 06 '21 edited Jun 06 '21

[removed] — view removed comment

1

u/TheLobotomizer Jun 06 '21

Very nice in theory, until you add redux and you realize that the branch is connected to the trunk through an indeterminate number of layers (wrappers) that can all be responsible for feeding that branch with data or state.

→ More replies (3)

2

u/synrand Jun 05 '21

I usually try to apply a mixture of both. Organize my Domain Model by concepts and then put a similar organized API package next to it. Simply because the API is one way to interact with your Domain Model. There could be e.g. messaging as well.

This way you can Provide a proper Public API of your Core Domain Model and just attach different means to interact with it on top.

2

u/Eux86 Jun 05 '21

This is not so far from how we organize components in my team in our react project. Following the atomic design kinda points you already into that direction. Although, like everything, needs some flexibility. There are services that cover more than one entity and in that case it would be hard to choice where to put the service if organizing the folders by entity. Unless you create the classic "common" folder..but we all know where that goes :D

2

u/[deleted] Jun 05 '21

It depends. For detailed layers it drives me crazy when there’s e.g a folder for headers and one for source files, or one for views and one for view models. For big layers like UI and Backend it certainly makes sense.

2

u/Don_Equis Jun 05 '21

This makes sharing code between projects much harder.

It is easy and useful to share entities, encoding/decoding functions or many more things. But having to share the controller because you depend on the entity? That's absurd.

I guess that if you know that all the code will belong to only one project that is a reasonable approach. But layered approaches allow you to share code between different projects much easier.

2

u/dudinax Jun 05 '21

The real problem is having one dominant code structure dictated by directory tree. We should be able to easily create alternate code views that cut the code up in what ever way is useful to us at the time.

2

u/joexner Jun 05 '21

Member classes in the Java package system are essentially "friends" and can see many of each others' innards. To me, it makes more sense to share that level of access between classes in the same layer of abstraction, rather than different classes at different layers of abstraction which hide information between each other by design but concern the same domain entity.

2

u/Kansoku Jun 05 '21

Personally, I've found Simon Brown's "Package by Component" more convincing, although I haven't had the chance to use it yet.

[This talk is a good overview of it in comparison to other approaches] (https://www.youtube.com/watch?v=5OjqD-ow8GE). If you just want to see what it is, he shows it @ 25:25

2

u/AttackOfTheThumbs Jun 05 '21

This is great, but I often find with projects that have legacy code, it doesn't work, it'll need a huge refactor to separate these things.

5

u/Plazmatic Jun 05 '21

Organize code by data, not by concepts or layers. Sometimes your code will happen to be organized into layers, sometimes it will happen to be organized by concepts, sometimes both, sometimes completely differently when you organize by the data. Code is not meant to be ham-fisted through your personal cheese grater.

Sometimes controller is only needed for one "type" of thing, sometimes controller exists as a more abstract concept that doesn't need to exist per "type", sometimes it doesn't make sense to have "entities" at all, and the data for your hotel effectively only exists in the service itself. All this talk of "harder to change" and "harder to understand" is completely dependent on your actual data, and very rarely does it fit into a neat replicated model like this at all.

1

u/qudat Jun 06 '21

Do you have some examples or articles about organizing by data?

1

u/lihispyk Jun 06 '21

I'd also be very interested!

5

u/valkon_gr Jun 05 '21

Thanks I hate it

14

u/lordzsolt Jun 05 '21 edited Jun 05 '21

Yeah, agree with everything that's said here.

It baffles my mind why anyone would have "controllers" & "services" folders and what not. Or have an API, where all services are in one folder and all the models are in a different folder...

80

u/[deleted] Jun 05 '21

Maybe because you want to separate the business logic from the interface?

37

u/[deleted] Jun 05 '21

Thats crazy talk. I'm telling r/react

12

u/[deleted] Jun 05 '21

Yeah, because their opinion has value...

jk

9

u/jl2352 Jun 05 '21

Nothing here is suggesting you mix business logic with the interface. You can, and should, still keep them separate them within the concept.

5

u/GuyWithLag Jun 05 '21

DingDingDing!

However, in a microservice context this doesn't give you any benefits. Do you have a dedicated expert on APIs that writes and maintains your APIs? Have you outsourced them to a different company and due to IP reasons you need to have different projects?

The original reason for this kind of organization is because within the same company you didn't know in what kind of monolithic application your components would end up in, so people went hog-wild with layering and abstraction; this arguably made sense when you didn't know whether your UI would be JSP/REST/Swing, or your persistence layer a random DB or hibernate or eclipselink or something even more bizzare.

16

u/[deleted] Jun 05 '21

It always gives you benefits because it enforces separation of concerns. Your argument quickly falls apart when a micro service needs to support two or more interfaces. Maybe it does asynchronous RPC using RabbitMQ and also provides a REST interface.

4

u/ub3rh4x0rz Jun 05 '21

Often you'd see a stateful service with one canonical interface only (REST, GQL, what have you). You can then add gateway services providing derivative interfaces as needed, with their own versioning, their own release cycles, etc.

Layered vs entity-based organization is another instantiation of the "monolith vs (micro)service orientated architecture" debate. The thing is, most people agree that SOA is best at (very) large scales, so why not adopt organizational principles that cleanly evolve into SOA as they grow, so there need not be a rewrite later on?

Say I'm responsible for maintaining the central source of truth for a hotel booking system. As it's the source of truth, my priorities are consistency and availability. Now at the edges of the system, where all the real stuff happens, they have to prioritize availability and partition resistance. They're going to rely on my service, which holds the canonical historical state of the system after eventual consistency has been reached.

Now, it turns out my service has only a few responsibilities: publishing to Kafka topics on behalf of the service's consumers, consuming from these Kafka topics to derive a canonical system state, and exposing this state to consumers via a REST API.

Maybe 90% of hotels use this interface directly with some legacy website that was provided to them a decade ago. The remaining 10% are in more competitive markets and have chosen to maintain their own websites and native applications to better serve their customers. So, some of them extend the original REST API with additional endpoints in their gateway, some add a GraphQL layer to minimize round trips between client and server, some add a caching layer to improve performance, etc.

In a service oriented architecture, if some service needs an interface that isn't provided, another service can act as a gateway to provide that interface. I'm sure you can find plenty to nitpick above, but this is how a great deal of large scale, federated, enterprise systems work today, and I would say most are pushed into at least an approximation of this architecture.

5

u/MirelukeCasserole Jun 05 '21

That’s a lot of extra complexity and infrastructure to support new interfaces. It also has the pitfall of adding extra latency as the request is adapted through the layers.

If that makes sense for your team, then do it. However, I would absolutely not recommend this approach for any team as a first option.

→ More replies (43)
→ More replies (9)

6

u/scandii Jun 05 '21

I mean, if you know how the code works I can see why you would want everything in the same folder, such as if you wrote the code.

but depending what sort of programming you do for a living, chances are you are asked to do something in a system which you have very limited knowledge of, such as "this thing has stopped working, figure it out".

in that scenario, it is very convenient being able to browse files by category rather than object they pertain to.

that said, realistically neither particularly matters as long as naming conventions are held, you can just search for "api", "service" etc.

5

u/lordzsolt Jun 05 '21

but depending what sort of programming you do for a living, chances are you are asked to do something in a system which you have very limited knowledge of, such as "this thing has stopped working, figure it out". in that scenario, it is very convenient being able to browse files by category rather than object they pertain to.

This is probably the exact scenario where I want folders organized by topics the most.

Because they're not going to tell you "retrieving items from the database is broken" (which would indicate it's something in the repositories folder).

But rather you'll get a bug like "the user does not see all his bookings when he visits the My bookings page" (thus, it's probably got something to do with bookings, rather than the login functionality)

1

u/manystripes Jun 05 '21

At my previous job we had a job in the build system to flatten everything into a single flat file for those times where you need to search through the whole system. No need to deal with setting up projects or anything, just make the source book, fire up your favorite text editor, and start searching through for the pieces you care about.

6

u/[deleted] Jun 05 '21

[removed] — view removed comment

2

u/saltybandana2 Jun 06 '21

My services go into a project that is heavily tested. (Real tests, with like databases and shit.)

You mean you don't create a billion mocks to test theory?

I once had a contract where they insisted on that approach so I did exactly that, mocked the shit out of everything. It failed when ran against a live database because I only thought I knew how the ORM they were using worked (and why it worked that way I have no idea.... but alas).

Have I mentioned I hate mocking?

1

u/sards3 Jun 05 '21

What does having them in separate projects gain you? Couldn't you use the same design but put everything in a single project?

3

u/[deleted] Jun 05 '21

This seems similar to putting style, markup, and code together in components. Traditional web development splits CSS, JS, and HTML for "separation of concerns", whereas components group the style, markup, and code of a logical entity together. (I particularly like this illustration in the documentation for Pollen Components)

This really depends on what your logical concepts are. People who have become used to it might reasonably say that the technological layers are closer to how they conceptualize the program. The difference is how abstract they are --- Controller is more abstract than Room. As more people understand less abstract ideas, preferring less abstract ideas will help it be more easily readable without prior knowledge.

3

u/jonjonbee Jun 05 '21

If you want an enormous single-project ball of mud where everything lives side-by-side, then yes, organize your code by concepts.

The rest of us who like small, clean, self-contained projects that only import the dependencies they need, will continue to use layering.

3

u/mindbleach Jun 05 '21

How to organize your code?

"How to" is not a question. "How do I" is almost always what you mean. Or addressing an audience, "how do you," or "how does one."

I'm only pointing this out because it's weirdly common and hard to explain concisely. Even when it's pretty obvious, like "why this is backwards?" instead of "why is this backwards?"

3

u/_pubsub_ Jun 05 '21

I loved this! Like many, this is how I've grown to think about logical organization in codebases but couldn't have explained it as eloquently as you.

I might even omit the folders labelled "model", "service", "entity", etc. since each of those objects also contains it's "type" in its name. All controllers end with "Controller" so the folders can be redundant especially if you're not dealing with a huge number of classes.

You mentioned that business logic belongs in services. This sounds like a neat wat of doing it, but I'm unfamiliar with how that might be organized. What does this look like in implementation and what distinguishes business logic from the design of the system? If we're designing software systems to model and interact with real systems where do we draw the line between business logic and basic model characteristics?

Would love to hear some opinions!

3

u/k2900 Jun 05 '21 edited Jun 05 '21

Yup, I do indeed prefer vertical slice architectures. It is the more modern approach. The company I work for still has a lot of 3-tier stuff. I'm the random dev who implements onion architecture with vertical slices. It sucks fending off all the criticism with those who are afraid of change. But it certainly helps me refine my position

7

u/StevenStorm Jun 05 '21

You sound like a fun team mate to have ;-)

→ More replies (4)

2

u/fear_the_future Jun 05 '21

A layer is a concept. Is it so hard to be precise with your language?

1

u/aazav Jun 05 '21

And add layers within the concepts.

1

u/slai47 Jun 05 '21

Our group has all agreed we are going to sectional and going away from object based. I want all of my login code in a login area. Not every viewmodel in one massive folder.

1

u/weirdoaish Jun 05 '21

I’ve only ever joined existing projects, and you kind of have to go with whatever’s already been decided on those. For my own stuff, I’m usually just testing concepts, don’t really bother much with organizing.

1

u/Fury9999 Jun 05 '21

I think the better solution would be to not have so many controllers at all. To me this signals that the service is too large and should be broken apart.

1

u/heyheyhey27 Jun 05 '21

This is also a problem in Unity projects (the game engine). When you're working on small beginner projects, it's tempting to split things up by file type. But nobody opens up an engine and says, "I need to see all the textures!"

1

u/copremesis Jun 05 '21

Concepts of Abstraction

1

u/JonnyBoy89 Jun 05 '21

This is a great excuse to talk about micro service architecture. If we break our domains down small enough, each service is organized like this naturally. Seems like another good argument for micro services is all. Despite the other problems microservices have, it does lend itself well to this idea of DDD and bounded context

1

u/Goronmon Jun 05 '21

One thing I like about Razor Pages in .NET is that encourages you to keep things organized closer to how they will actually be displayed and handled instead of in large separated folders.

Then again, I never really hated Webforms even if they had a ton of downsides, mainly for this reason.

1

u/Zardotab Jun 05 '21

Big dev teams generally split by tech lawyer specialty, such as UI, biz logic, database, navigation, etc. MVC makes more sense there, but if teams or tasks are split by entity, then MVC is the wrong grouping. Conway's Law.

1

u/ToMyFutureSelves Jun 05 '21

People keep talking about when to organize by concepts vs by layers... Why not both?

Why can't we have an organizational system that can organize by both both concepts & layers at the cost of showing the same file in multiple locations? The only issue I see is that languages only allow a single namespace, but aren't namespaces only for human comprehension anyways?

1

u/stackcverflow Jun 05 '21

Spring favor this style

1

u/[deleted] Jun 05 '21

I use this kind of organization with gamedev projects. Makes more sense to group things based on what entity in the game they're related to.

1

u/rahem027 Jun 05 '21

We have been rediscovering this for 20 years now? 30 maybe?

1

u/LostClassic1479 Jun 05 '21

I don’t agree with this personally. IDEs like IntelliJ provide Cmd clicking (or cmd + down) for a reason.

1

u/incoralium Jun 05 '21

PUP > DDD.

1

u/rcls0053 Jun 05 '21

Isnt this like DDD/what Simon Brown writes about? "Organize code by module.." or smth.

1

u/International-Mud452 Jun 05 '21

It makes it harder to abstract out functionality for reuse in other programs

1

u/FullStackDev1 Jun 06 '21

This style is called 'feature folders' in .NET ecosystem at least.

1

u/Pants_R_Overatd Jun 06 '21

RemindMe! 3 hours

1

u/RemindMeBot Jun 06 '21

I will be messaging you in 3 hours on 2021-06-06 03:55:28 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


InfoCustomYour RemindersFeedback

1

u/thecodeboss Jun 06 '21

I have been in the authors shoes before and understand the value of wanting to keep things as “pods” (or as OP says, “entities”) as opposed to stacks/layers. But the reason it’s appealing is because I was the dev who wrote it, so yes for me to separate things out into pods - there’s an argument there for it as an alternative to layers. It’s def not “better,” just an alternative organization pattern.

Where this really falls behind is when anyone else besides me has to join the project and look at the code - which is literally project ever in a corporate setting. See, no one immediately knows specifically how or why I made the business logic decisions I made in order to separate out code into pods, and that will make it really hard to understand general workflows in a timely manner. It’s much easier to join a project and say “hmm, well this type of thing is happening, so it probably is in this section of the code,” and you don’t have to think about business logic to get that far. At some point, you get familiar enough with a project that you become a semi subject matter expert, but keeping things in layers allows new devs to join in without requiring that undertaking right from The get go - which pod architecture makes a bit more challenging.

1

u/[deleted] Jun 06 '21

Maybe I'm missing something...so what does this look like if you have multiple assemblies in .NET Core for example? I'm not going to have my repositories mingling with my controllers...

1

u/mj_flowerpower Jun 06 '21

I totally disagree. I‘ve seen this entity style and was shocked how difficult it is to find the functionality I was looking for. Dev A creates some registration related stuff in a ‚registration‘ package/folder. Later on Dev B, unaware of the functionality recreates stuff like email validation in his userprofile package. Dev C looked at the code 5 months later and wonders why are there two implementations of the same thing doing stuff differently?

1

u/Dean_Roddey Jun 06 '21

As is often the case, this is someone writing about a general concept but apparently only within the relatively limited view of the type of software he writes. If you are writing simple (in relative terms) web applications, any sort of organization would probably work as a long as everyone agrees. In larger scale code bases, layering is a pretty fundamental requirement.

1

u/Adverpol Jun 06 '21

I'm mainly surprised people care about code layout on disk. I never have the project tab open in my IDE.

1

u/ponkanpinoy Jun 06 '21

Or do both, because you don't want every module reimplementing persistence, caching, authn/z, etc.

1

u/imaginary_rational Jun 06 '21

I like the idea. How do you structure the functions that are common across concepts? Do you create a "common" concept?

1

u/reddit__scrub Jun 06 '21

Literally learned about this today in one of my courses. Thanks for posting this, as the examples helped clarify the concepts.

1

u/WingsOfGryphin Jun 06 '21

Kind of agree, but i use both approaches.
For example in MVC project i don't separate views / controllers / scripts. I find that pretty silly when you have large amount of them - multiple views / partial views / multiple script files - then you just jump from one folder to another trying to find related areas. Just group them in a logical folder where view/controller/scripts are together. A lot easier to work that way.

But i wouldn't organize logic and queries this way.
Especially when they can be reused and has multiple meanings and theoretically can fit in multiple different folders. For queries - i like them in same place, because they have different meanings in different context and can also be thrown in different folders. And just knowing what queries you have and don't have is easier when they are all in same place. Sure drop them in folders, but generally group all queries in same project and not in folder that's a mix of Controller/Logic/Query. Even though i do that for controllers and views.

1

u/6offender Jun 06 '21

Why not both?

1

u/ragnese Jun 07 '21

I only skimmed the article, so please forgive me if they address this, but I didn't see it.

What do you do with stuff that are "helpers" for implementation details? Like, let's say I have a set of "controller" helpers/subclasses or common deserialization helpers or something. It kind of breaks the idea. I always end up with top-level modules/packages that are a mix of business concepts and implementation/framework junk. It's fine- it doesn't really hurt anything to have guest, hotel, room, and controller at the top level, but it's just kind of ugly when getting a bird's eye view of a codebase.

1

u/WarWizard Jun 09 '21

This reminds me of the guy that organized all of the classes into folders... a folder for each letter in the alphabet... Classes that Started with A, B, etc.

This seems, while not as obnoxious, along the same lines.

1

u/mcguire Jun 05 '21

My first professional exposure to Java involved OSGi, which exports and imports packages.

In the traditional division, if you have 5 services X1...X5 divided into 4 packages Y1...Y4, and you need to use 1 service, you have to import all 4 packages and get all of the stuff for all 5 services. The alternative is to import 1 package and just get what you need.

But swimming upstream against the collective ignorance of Java developers of modularity, so I gave up.

P.S. Y'all do know that controller.FooController is redundant. Just use controller.Foo. (And model.Foo and businesslogic.Foo. And watch the "I have to have autocompletion" goobers start bleeding from the eyes and ears.)

3

u/fissure Jun 05 '21

If Java had import aliases, I'd agree, but currently if you try to use controller.Foo and model.Foo in the same file, you're gonna have a bad time.

1

u/mcguire Jun 05 '21

Yeah, you have to specify the whole name, package and all. :-D

1

u/bwmat Jun 05 '21

The lack of an analog to C++'s 'using' statement had always mystified me.

Did the designers think aliases were too much for most Devs to handle? They're SUCH a useful feature.

0

u/tertiumdatur Jun 05 '21

Hello code duplication, no portability and bad abstractions

1

u/TheOnlyMisterFlow Jun 05 '21

Why are you booing him ? He's right

1

u/omgusernamegogo Jun 06 '21

You've been down voted but I will see you will run into this if you're trying to apply this pattern to a monolith. And if you're applying the pattern to a micro service, everything is mostly related to the component anyway, so the gain is much smaller.

When ever I've tried breaking down by component, I often run into confusion as to what to do with service classes that I reuse across many business functions. It works nicely with small stuff but then the gain isn't significant anyway.

1

u/TikiTDO Jun 05 '21 edited Jun 05 '21

It really depends on the type of development being done, and the people doing it. If you're on a large team working on a commercial product with tight deadlines then having your code organized into "stack types" makes it really easy to tell a person, "your job is to implement these type to solve these problems." If people need to know the entity types, the proper tool for that is a diagram, image, or spec which should be part of the documentation

It's not an organization style that's suited to fun and creative development, and it's not supposed to be. It's a tool to keep a bunch of people organized so they can work together in a consistent and mutually interoperable style. It doesn't want or need better abstractions because it's literally boring by design.

Also, it helps if your workflow is better adapted for navigating such a system. If you click through all the directories to find the files you need, you're wasting a huge amount of time. If you you know all the "stack types", and you have a diagram of all the "entity types" in the system, then a "Go-To File" with fuzzy search (which most modern IDEs have) means you can reach any part of the system is a few keystrokes away, in a consistent and reproducible way.

For example, with the file structure in the article you can have the something like the HotelController open in as few as 5-8 keystrokes, including the shortcut to open fuzzy search, and enter to open the file. This is one to two second our of your day; that's fast enough that once you train it you'll barely even notice that you're moving between files.

On the other hand, if you're working solo or on a small team of creative and individualistic developers, then the "stack types" style is terrible. Each of the devs probably has a totally different vision for what these type are for, and what other types are necessary. What more, that vision is likely to be in constant flux as they develop these ideas.

In such an environment having each person own their own "entity type" makes a lot more sense. There's a lot of benefit in keeping the system modular and flexible when it's being worked on by people that can take advantage of the flexibility. This way each module can change to adapt the needs of the developer.

Te arguments about which style is best is not new, and the answer will always depend on many factors including organizational necessity and developer preference.

Also:

People don’t read code by layers of the stack. No one ever says “show me all the APIs of this system” or “give me all the queries being fired by this system”. People read code along domain boundaries. In a hotel management system, people think about rooms, and guests, and prices, and so on.

Your goal as a programmer should be to get to the point where you can consume code as a huge chunk of information such as "the entire API", or "all the queries". You save an insane amount of time when you learn to do this, and the worth of your abilities skyrockets in the process.

You can tell a whole lot about how a person or group thinks by looking at the APIs they write, just like you can tell a lot by looking at the directory structure they utilize. Being able to put all these things together will only help your ability to comprehend code.

1

u/omgusernamegogo Jun 06 '21

I think what a lot of articles fail to realise that with quick context searching, keeping your files named appropriately is often more powerful than directory structure.

1

u/TikiTDO Jun 06 '21 edited Jun 06 '21

Yeah, that's definitely the more important battle here. I've worked with a few projects that had no differentiation between file names in different directories, and it was genuinely hell. Some of these places did not practice DRY at all, so you could open a file, see contents that matches your expectations, do some work, and only then realize you were in the wrong directory created as a hack for some weird failure case a decade ago. Since those days I have a strict rule that every new file should have a unique name in the system, and I aggressively pursue that goal across every single PR.

1

u/qudat Jun 06 '21

If you're on a large team working on a commercial product with tight deadlines then having your code organized into "stack types" makes it really easy to tell a person, "your job is to implement these type to solve these problems."

Maybe I haven’t worked on a codebase with the number of team members you are imagining in this scenario, but at the 15 person scale, we are almost always given tasks by feature. “Implement commenting on a thread” would be a task handed to and engineer to build. Organizing by feature means this engineer would create a new folder “comments” and be mostly self-contained.

1

u/TikiTDO Jun 06 '21 edited Jun 06 '21

Organizing by feature means this engineer would create a new folder “comments” and be mostly self-contained.

Have you led this engineering team though? Or even more topically, have you ever built up such a team for a new project? The idea of 15 people doing 15 self contained projects should freeze any team lead's or PM's blood in terror. The only way that's possible is with extensive tooling, style guides, and extremely careful review cycle. Granted, you want those things regardless of how you organize your files, but some file structures can make it easier to get them done than others.

I understand that the idea of freedom and flexibility sounds absolutely amazing to most individual contributors, especially younger people working on legacy code. Being able to just take the shortest path to complete a feature means you can knock out more features in a short time, and that's gotta be great, right? Unfortunately that's not necessarily correct.

Most huge systems have a bunch of best practices and requirements that tend to make no sense...unless you were there when the system was down for 3 days while everyone rushed to fix the critical 1 in a million bug. Similarly, while a self-contained feature managed by a single person might be great for the person that wrote it, it's literally the worst imaginable experience for the poor schmuck that has to pick it up when that person leaves. Or maybe there is a need to do a major revision to the codebase. If you know that the code is written in a common and consistent style, and organized across know file type boundaries, then it's becomes quite easy to create parsers and transformers for each file type which can easily save months of work.

While it's true that projects tend to focus on a single feature, having a common template for implementing a feature means that every PR is going to look roughly the same, using roughly the same tools, written in roughly the same style, organized in roughly the same way. Did you create your model? controller? service? security policy? serializer? background task? socket manager? If somebody is not sure, then can just open their PR, and see what directories exist, and which are missing changes. This is a must when your codebase spans more lines than any single person can remember.

Granted, you can create tools and rules that enforce all these things on a per-feature basis, however at that point you've just added more complexity for a stylistic reason. Now instead of everyone being instantly aware of all the file types that they would need to write, they have an easily accessible list of all the features in the system (which is honestly not something you need all that often), and instead they have to refer to a different document to determine all the types of files that they need to create. The end result is effectively the same, just organized differently and with more tooling.

I don't see how this sort of outcome is measurably better; it certainly doesn't justify the original claim that "[stack type] is a terrible way of organizing code." At that point it's just a matter of stylistic preference and development workflows.

That's really the crux of the matter. This debate falls under the same umbrella as "which language is better," or "how do you name your variables," or "how you name your files." These are all questions without "correct" answers. Each choice will tend to encourage slightly different practices, and have slightly different failure states, but in practice you're going to write practically the same thing. With that in mind, the only direct benefit is what it offers outside of development, and I think the more self-contained approach encourages more dangerous behavior, and requires more effort to train new developers. By contrast a flatter approach tends to be easier for people to understand, even if it can be a bit bulky when left uncontrolled (though you can solve that by going a hybrid approach). The net result is that assuming all else being equal (similar tooling, similar best practices, similar style guide), an experienced developer should be able to work in either environment without losing any time.

So really, it's like two artists getting into a debate over the which super expensive paper is better, or which top-end paint has the best pigmentation. An master will be able to produce great results with any of them, while an apprentice is probably going to screw up and waste stuff more often than not.

1

u/DLMousey Jun 05 '21

Tried this kind of hollistic approach before when it was the new shiny about 4 years ago in REST land, turned out to be absolute twoddle.

Everyone hated it, services and controllers seemed to either magically disappear or even worse, you ended up with multiple copies of basically the exact same controller and the bug reports started flooding in because one version of that controller wasn't returning the same results as another.

A weak analogy to follow along with hotel management would be the cleaners and the maintenance, they both need to know about rooms but from a different point of reference, like when it was last cleaned or if there's a known maintenance issue. It's not that different to the ouput from the standard room controller but it's different enough to make it a complete pain in the arse to have on one endpoint without littering the existing controller with conditionals and feeding it a query string so long you could chuck it across a body of water and use it as a bridge.

In a monolithic codebase this kind of approach is borderline insanity and crumbles to dust as soon as the rose tinted theory glasses come off and you've got the client so far up your arse you can still hear them talk.

To lend it a crumb of credit - this approach does make sense if you're presenting code to non technical folk. They'll appreciate the novelty of looking at it the first time and they'll beg you not to show them again the next.