Stop Using Booleans in Your Code! | Code Cop

  Рет қаралды 38,984

Nick Chapsas

Nick Chapsas

Күн бұрын

Until the 30th of September get 30% off any course on Dometrain with code BTS30: dometrain.com/...
Subscribe to my weekly newsletter: nickchapsas.com
Become a Patreon and get special perks: / nickchapsas
Hello, everybody. I'm Nick, and in this episode of Code Cop, I will talk about boolean blindness and why it is not what the author of this LinkedIn post described.
Workshops: bit.ly/nickwor...
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: github.com/Elf...
Follow me on Twitter: / nickchapsas
Connect on LinkedIn: / nick-chapsas
Keep coding merch: keepcoding.shop
#csharp #dotnet #codecop

Пікірлер: 376
@mateuszfiedorowicz6983
@mateuszfiedorowicz6983 6 күн бұрын
One day the "advice" will be so horrible that at the end of the video you will say "Stop Coding".
@jcx-200
@jcx-200 6 күн бұрын
That's an April Fools video for next year sorted
@demarcorr
@demarcorr 6 күн бұрын
big true if false
@xhavierrhovira2858
@xhavierrhovira2858 6 күн бұрын
Ok, now I want a video of Nick refuting those *blergh* CleanCode™ tipes from Uncle Bob
@BamYazi
@BamYazi 6 күн бұрын
Uncle Bob is the Life Coach who tells you how to live whilst having $50k debt, and regularly misses his car repayments .. his job is to make up problems with code
@brianm1864
@brianm1864 6 күн бұрын
I agree with you. If the boolean is obvious (apply discount vs do not apply), then go with the boolean. If it's not obvious, like "apply discount pro-rated to all items" vs "apply discount to highest price item" (stupid example I know but best I could come up with on short notice), then an "applyDiscountToAll" boolean can be confusing, since it's not obvious what false does. Then you use an enum.
@mattymattffs
@mattymattffs 4 күн бұрын
Better example would be apply discount, apply upcharge, none. That kind of business logic can be complicated fast
@demarcorr
@demarcorr 5 күн бұрын
the more experienced I get (15+ years at this point) the more I have come to understand that these absolutes are meaningless. Uncle Bob is a very smart man selling snake oil in many cases. If it makes sense to use a bool, use the damn bool, otherwise use something else, and just keep it simple.
@fappylp2574
@fappylp2574 5 күн бұрын
You have the 15 years of experience, you can judge when to keep it simple, most people don't. There are a bunch of kids out there hate Clean Code because it intrudes on their ability to just do whatever they want like in their hobby react projects. They disagree with it because it's the "punk" thing to do with advice from boomers.
@danpaun2279
@danpaun2279 6 күн бұрын
avoiding boolean parameter and splitting in two functions often will mean to have the "if else" statement at an upper level :)
@CodeAbstract
@CodeAbstract 6 күн бұрын
thats exactly what Chapsas said
@gileee
@gileee 6 күн бұрын
No you wouldn't usually. What people do is they have some functionality that deserves it's own function. But then they start using that functionality in other higher level function but they require slight difference in behavior and instead of making two clear lower level functions (where one can still call the other for the common functionality) they decide to use a bool param and use it to enable the change in behavior. You're adding an if where there doesn't have to be one and it's actually slower.
@stevenbroshar7948
@stevenbroshar7948 6 күн бұрын
Exactly. That makes flow control clearer to the reader.
@evancombs5159
@evancombs5159 6 күн бұрын
@@gileee yeah, when you have this situation you have two options. 1. Break it up into two functions with similar but slightly different code. 2. Take a page from functional programming, and pass in a function that represents the difference between the two processes.
@DiegoMenta
@DiegoMenta 6 күн бұрын
You could also use two types
@trader548
@trader548 4 күн бұрын
Project on day one: There are only two types of discount, discount or no discount (booleans are everywhere in the code base, all public API, etc) Project on day one-hundred: We have currently 673 discount schemes, depending on the customer type, geo location, day of week, phases of the moon... 😆
@Tldr205
@Tldr205 3 күн бұрын
True but hopefully a refactoring occured when the business logic changed to reflect it and a new and more suitable solution was found perhaps a discount calculator class or something like that.
@smathlax
@smathlax 6 күн бұрын
I think in general people need to stop saying that there is any one correct way to program. Even if something is a good rule of thumb the vast majority of the time, that doesn't mean it does or should apply to every situation. Sometimes it's better to forget these "best practices" and just use your common sense.
@stevenbroshar7948
@stevenbroshar7948 6 күн бұрын
Sortof agree. But don't forget the advice. Follow it usually but be willing to make bold choices when you think it's wise.
@evancombs5159
@evancombs5159 6 күн бұрын
While true, we have to understand there is a learning curve to programming, and this isn't something that most people will understand right out of college. These design rules are training wheels for inexperienced coders. At some point you can take them off, and you'll have an understanding of when to use them and when to break them. That understanding isn't something that comes naturally, it is something that is learned.
@smathlax
@smathlax 6 күн бұрын
@@evancombs5159 I don't think you should use a rule if you don't know why it's there, and the only way you'll know why it's there is if you have the fundamental understanding. Once you have that you can look at the rules and decide if you want to use them for each specific case.
@smathlax
@smathlax 6 күн бұрын
For example when I was new I learnt the "keep your methods small" rule by having absolutely massive methods to the point where they became unreadable and extremely difficult to change. Because I learnt this the hard way, I now have the nuance that sometimes it's okay to have large methods, for example when initialising flags/objects at the start of a program. I don't think it would be helpful to just be told "keep your methods small" without having any idea why you should do that.
@mattymattffs
@mattymattffs 4 күн бұрын
The only correct program that exists is an empty file
@yogibarista2818
@yogibarista2818 6 күн бұрын
Clean code appears to have fallen to the same fate as Martin's other evangelisms - e.g. Agile. There are virtues in patterns, but once they become a religious dogma that all code needs to be coerced into conforming, they lose much of their value. The argument of avoiding passing booleans because it means branching inside a function, as apposed to branching outside to call separate functions, appears on the surface to be a case of following a pattern for its own sake.
@alexbarac
@alexbarac 6 күн бұрын
There's a coding principle called KISS, with which the author of this advice does not seem to be fully familiar...
@DevelTime
@DevelTime 6 күн бұрын
Why not? KISS does not mean writing code in assembler and risking that you are absolutely prone to simple typos.
@fusedqyou
@fusedqyou 6 күн бұрын
@@DevelTime What are you talking about? Point is that you don't need to over engineer code with enums when you should just use a bool
@tedchirvasiu
@tedchirvasiu 6 күн бұрын
@@DevelTime I think writing code in assembler is definitely not simple and the other s.
@Ilix42
@Ilix42 6 күн бұрын
Ah yes, Knights In Satans Service.
@alexbarac
@alexbarac 6 күн бұрын
@@Ilix42 You're wrong, it's actually Keepers of the Solid State.
@RealCheesyBread
@RealCheesyBread 6 күн бұрын
In every project I work on, I end up replacing about 50% of boolean fields and parameters with an object, struct, or enum over time as the project matures. It's not because I am trying to follow some rule but because something eventually ends up requiring me to do so to avoid obliterating code readability and maintainability. Booleans just don't contain enough information to be useful in many situations. I'm not saying to avoid using them. I am just saying you should keep in mind that there's a 50% chance you're gonna end up needing to replace the boolean(s) with something better in the future. Don't write your code in such a way that you're gonna be fucked when you decide to replace the boolean later.
@Tldr205
@Tldr205 3 күн бұрын
But is this not the way it should be? Implement simple logic, and refactor to more complex when the business requirements need it?
@vchap01
@vchap01 6 күн бұрын
An enum can provide additional values like GoldDiscount and SilverDiscount. But for business logic that includes orders and pricing, it would make sense to use a strategy pattern instead of conditionals. For simple/POC projects, a boolean is perfectly fine.
@404HumanNotFound
@404HumanNotFound 4 күн бұрын
I think it would be better to have a method that calculates the discount and passes the discount into the ProcessOrder method, which always does the discount, even if there is no discount.
@Palladin007
@Palladin007 6 күн бұрын
With CleanCode, it's not the rules that count, but the fact that we deal with these rules, even if we don't follow them - hopefully after careful consideration.
@SteffenSkov
@SteffenSkov 3 күн бұрын
To uncle Bob's defense I think it is worth remembering where he comes from. Being "a senior" developer myself, I have also been through that period of time where object oriented programming was new enough that everybody were designing class hierarchies so deep that they were reaching hell. People were writing methods several hundreds of lines long. Nobody paid attention to number of arguments for functions/methods. My impression is that nowadays new developers are learning better OOP skills during their education, and therefor those somewhat extreme measures put forward by uncle Bob seems completely out of place. There are still some valuable points to what he is saying/writing, I think.
@kikinobi
@kikinobi 5 күн бұрын
Sometimes you really really just need a simple boolean and you will never have to change it
@local9
@local9 6 күн бұрын
enum traps are real and can create an even more annoying mess. Edit: Seeing Uncle Bob hurt, I read through his books when I was being 'forced' to learn Java...
@SuperLabeled
@SuperLabeled 6 күн бұрын
LinkedIn has a setting enabled by default called "Use my data for training content creation AI models". I firmly believe developers are trolling linkedin to train bad AGI.
@colejohnson66
@colejohnson66 3 күн бұрын
The post's "reasons" already look AI generated. No sane programmer would write that.
@johnbennett1465
@johnbennett1465 6 күн бұрын
Nick, I agree with your comments. There is one issue you glossed over. If the parameter will usually be a constant, splitting into two methods is probably good. If it will usually be computed, it makes more sense to be a parameter.
@doichev-kostia
@doichev-kostia 6 күн бұрын
Can’t you just pass the discount instead of the bool? It can be an unsigned integer (uint8) that will indicate the percentage. Well, the parameter should also indicate that those are percentages we are talking about. If you don’t want any discount - pass 0
@bnm0312
@bnm0312 6 күн бұрын
A Boolean is simply a bit of data that the called code uses to perform its function. So documentation is mandatory if you're writing an API and expect those writing code to call it know what to pass in and why. The values expected for the method to receive need to clearly defined and what the values mean, and how those values can affect what happens in code. Enums don't work well for public API's, because they get converted to integers, which mean they need to be documented as well. What does 3 mean? The developers on both sides of the calling/called need to be clear with the intent of each of the parameters being passed. What the data types are is insignificant if the knowledge behind the parameters is understood.
@MrMatthewLayton
@MrMatthewLayton 3 күн бұрын
"Call one method in the true case, and the other method in the false case" just suggests that the if/else moves up a level to the function that calls those functions. As a mid-level engineer, my tech lead also told me that boolean arguments should be avoided, because when you read it at the call site (assuming that you either haven't been provided with a named argument, or using a language where named arguments aren't supported), then you don't know what that boolean means, without looking at the function itself. In contrast, an enum provides additional information that expresses the intent of the argument (as per the LinkedIn post)...at least, that was the rationale I was given. Neither approach bothers me.
@antonmartyniuk
@antonmartyniuk 6 күн бұрын
Nick's mimics in this video are hilarious
@marktrinder626
@marktrinder626 5 күн бұрын
I’m always amazed how so much clean code is thrown away and rewritten. 😂
@ghevisartor6005
@ghevisartor6005 6 күн бұрын
What about the feature of editors to show the label for parameters? To avoid naming the parameter specifically, if you dont have many of them that are optional and need to choose. Alzo Zoran Horvat have videos specifically on discounts and use type pattern matching with objects. I guess it depends on the complexity of the domain.
@pseudohyena
@pseudohyena 6 күн бұрын
This. I'm so tired seeing all those boomer pieces of advice. Add prefixes here, shorten names likes that, don't use this, but use that, write comment for everyting... And their justification is "It's more readable, debugable etc". Ffs do you all write code in Notepad or something? Every modern IDE has features that help you understand what is what. Without you making code worse with their advice. And then the same people are going to write code like this: int32 GetCntPrdNum(int32 p_Num, FooBar p_Prd); To then add 10 lines of comments to explain that "Cnt - Count Parameter", "Prd - Product Parameter" etc. I've seen it, I hate it.
@winchester2581
@winchester2581 6 күн бұрын
Sure it depends, but the example from the video cannot explain the meaning of the advice. However, commenting on Zoran's videos, there are valuable examples like replacing `IsPublished` property of `Book` class with more robust representation
@lukasvavrek2909
@lukasvavrek2909 6 күн бұрын
In my team, I would much rather see code optimized for readability in GitHub (i.e. for PRs) than relying heavily on an IDE configuration. Other than that, I agree - start simple, and introduce the complexity gradually based on your needs.
@RoyBarina
@RoyBarina 6 күн бұрын
I think you should split your comment into two distinct comments
@davidgncl
@davidgncl 6 күн бұрын
If there's a chance that the logic could change in future, i.e. the discount rate will change, then an enum is on the right track but it's still wrong. Strategy pattern would be better there.
@frankroos1167
@frankroos1167 5 күн бұрын
Too often I see people who want a single, simple solution for all problems. Not only do I see that desire, I also see that educators need books to do their thing. And it's easier to put single, simple things in books. That's what causes many cases like this: "Oh, I see a problem in that corner over there. Ah, I know the solution. And now that solution is the answer to everything." (And there I was thinking that it was 42.) I sign my emails with the quote "When all you've got is a Hammer, every problem looks like a Nail" as a reminder that a single solution doesn't exist. Instead, I have a toolbox (or rather, a toolcart) full of tools. For each problem, I need to find the right tool. Sometimes, it is to avoid a boolean. And at other times it is to use a boolean. Teachers would do well, not to teach just a single tool, but to teach multiple tools, and how to decide which tool to use. And I think Nick Chapsas is helping a lot with that. So, thank you for spelling it out in video's like this one.
@F1nalspace
@F1nalspace 6 күн бұрын
We use a lot of booleans for method arguments in our production code and one boolean is not a problem, when it has a good name. As soon as we have more boolean, regardless of the order - we replace all booleans with an flags enum or better, separate the method into multiple ones, if possible (often this is not possible, due to duplicate code). But there is always a point, where you have to glue them together, so in the end - you don't gain that much by splitting methods. I personally like booleans in methods or functions and as soon as i have more than one directly following the other one, it is a code-smell and i replace it with an bit-flags enum instead.
@avisian8063
@avisian8063 6 күн бұрын
Flags are great, but I also consider them code smell. As many times as I see them well utilised I see them as a band aid for an overly complex method that needs splitting
@DevMeloy
@DevMeloy 6 күн бұрын
Each case is different, but in general passing a Boolean is a last result and to me is a sign that some rearchitecting is in order. For the example Nich shows, I'd rather pass in an optional param "existingDiscount" if possible. Also, I don't understand the hate for "clean code", sure some things Bob takes too far but don't throw the baby out with the bathwater because you don't like the guy.
@avisian8063
@avisian8063 6 күн бұрын
@@DevMeloy the hate is for Clean Code(tm) not clean code. If you get me?
@DevMeloy
@DevMeloy 6 күн бұрын
@@avisian8063 I've watched clean code(tm) and walked away with some good knowledge, do I subscribe to every commandment? No, but it seemed like the hate for clean code came from a dislike of Bob not necessarily his views on code. Not being argumentative, I honestly didn't look into what "Bob did" to piss everyone off... And honestly don't care.
@avisian8063
@avisian8063 6 күн бұрын
@@DevMeloy no, I mean Clean Code(TM) as a saleable product. Like capital A agile. It's the grifters who treat it like its commandments that are annoying (and who have followers who treat it as gospel)
@holger_p
@holger_p 21 сағат бұрын
As a soft advice, a recommendation, this is good, it doesn't deserve a hard stop, as in your title. It makes code more readable, und avoids bugs coming in from a programmer getting easily confused. if (item.state==disabled) is more clear to read as if (!item.IsEnabled) .. it's better, but I would'nt call it enhancement.
@ryankueter9488
@ryankueter9488 6 күн бұрын
The context of the code matters. In many instances, automatically using Enums could be over engineering. If it only requires a Boolean, then use that. In many instances, an Enum works well, especially for parameters. Or if something else would work better, then use that. But don't implement unused code features that could lead to confusion, like implementing a base class that contains no functionality, or an Enum where a Boolean value would suffice, or applying a more complex pattern, such as creating a class that returns a true or false value. That advice came from a mid-level developer aspiring to be the teacher instead of continuing to be the student.
@gppsoftware
@gppsoftware 6 күн бұрын
Having worked in C++ for about 15 years, then 20 years in C#, I think I can see where the 'logic' around booleans and enums lies. In C++, FALSE is an integer with a value of zero. TRUE is an integer with any value other than zero. In BASIC, FALSE had a value of zero and TRUE was either -1 or +1, depending on the BASIC implementation. In C#/,NET, booleans have their own 'type' of true/false values and are not merely int values like C++. That means in C#, a bool can only have two values and you can't 'functionally override' it like you could with C++ to return extra values. In C++, people used to write code to return boolean values from functions. When they discovered they needed to return a third value, they did exactly that: 0 was FALSE, 1 was TRUE, 2 might be the third value and so on. C++ supported it because all values were ints. Better programmers realised that this wasn't a good idea so either adopted properly defined return codes as #defines, const's or enums, the latter two you can do in C#. I would suggest that 'mandating' the use of enums around this is not a good idea. Internally within code, it is fine, but the moment you start exposing it to other apps or through webservices, you often get text values exposed which impose implementation rules on the calling app - which you need to think about - sometimes this is right, sometimes it isn't. A bool true/false return is fine if that is all you want, but I would suggest that const/enum (take your pick) should be used wherever there is any possibility of the number of return values changing, especially to more than 2. At the end of the day, pragmatism applies.
@PbPomper
@PbPomper 6 күн бұрын
I agree that passing down flags to a method is a definite code smell. If you pass a flag, you probably need two different methods or encapsulate that flag (for example create an Order object and pass that down). The advice itself isn't even that bad, but the example they show is (like you said).
@marcusmajarra
@marcusmajarra 6 күн бұрын
My best coding advice: beware of coding advice that starts with "never" or "always". Instead, look to the "why" of the advice as it will instruct you on what some good motivations can be. From there, you can better assess how a specific situation will be best fit by a particular code style. Regarding passing Boolean parameters, I agree that they can sometimes lead to ambiguity if the code doesn't read clearly. That being said, it is sometimes a necessity, especially if the caller has no knowledge of when in the method call the conditional logic should be executed, which is likely to be the case when you're invoking the method of a different class. You can certainly opt to create multiple methods with different responsibilities rather than introducing a Boolean parameter, but this doesn't scale well if there need to be more options in the method call. Exposing a different method call for every single permutation will litter the API, which can be a real pain when designing a class library for public use. Generally, if a particular operation has a good number of different permutations in terms of how it's executed, I will tend to favor a parameter object to encapsulate all the various options in the call and delegate the responsibility of dispatching the work to the callee since they're more likely to be an information expert on how to execute the operation.
@MrKlarthums
@MrKlarthums 6 күн бұрын
You could instead create a type to encapsulate all necessary state. This is really a non-issue for one boolean, but when you have several, you get a combinatoric explosion and good luck providing unique names to have a handler method for each code path. Or you could just...hover so your IDE will tell you what each parameter is or run an IDE feature/extension which shows a label for every parameter.
@maxsnts
@maxsnts 5 күн бұрын
The advice could be useful if different reasons were given, as it stands, not so much. I have used this in two situations: - Its really really obvious that new options will arrive soon, starting this way can prevent expensive refactors. - If you want to persist that indication in the database, an numeric enum can help keep track of things
@BobKatLife
@BobKatLife 6 күн бұрын
Sucks when you have to tell the boss you can’t answer his question because you failed to consider the need for a “not yet selected” option.
@DevelTime
@DevelTime 6 күн бұрын
This time I don't agree with you, example being 2:36 -- and this is why I use only wrapped ids -- NumberId, GenderId, WordId, etc. There are no "raw" ints used as ids in my code for a reason. Of course stating "don't use bool" is somewhat too strict, but I am all in for "limit their usage". The example provided is not good because of the reason you mentioned -- this is basically one fragile code (because of ambiguous type) exchanged with another fragile code (because the type is now open but it is handled like boolean). But the surface of the method (signature) is way stronger in the second case -- it is "readable" vs "bomb-proof", there is no chance in the second case to mistakenly pass for example "IsForeignerCheckbox.Value" instead of "DiscountEligible.Value". So in short, I fully support the idea of using enums (but not in the sense as presented in the lecture included), it is counter measure against human errors, being tired, not fully understand what goes where, typos (consider also that today we usually type 2-3 characters, and the rest is added by IDE).
@JasonBoissonneault-j4i
@JasonBoissonneault-j4i 3 күн бұрын
Many tutorials and critiques are used as self-promotion for a portfolio or CV. An easy way to present yourself as an expert or authority is a critique of common practices or simple patterns while speaking confidently about invented absolute rules. A developer named Zed Shaw really exposed this tendency years ago.
@yorkaturr
@yorkaturr 5 күн бұрын
Clean code means readable code. If you need to come up with your own data structure for every parameter you use, it's a nightmare to debug. Maybe it's just me, but I like to use basic datatypes whenever possible. It's especially good in the backend if you can match your datatypes in code to datatypes in the database.
@coolmenthol
@coolmenthol 6 күн бұрын
Gatekeeping in the software industry is one of the worst things. Both approaches have their pros and come from a good place. The simple boolean and the more complex example are just different ways of solving problems. I bet the author has years of coding under their belt, probably with some solid Java experience, and can abstract things so much that even their coffee order needs a design pattern.
@Rolandtheking
@Rolandtheking 6 күн бұрын
I think both cases are valid, the boolean one is shorter, but allows any boolean to be passed in, even if it represents something else. Also a boolean cannot easily be extended, perhaps if more discount options arise. If the advice is to replace al places where we pass in a boolean, it is probably not worth it, and miht make the code needlessly longer.
@maacpiash
@maacpiash 6 күн бұрын
return falsen't;
@ThomasAngeland
@ThomasAngeland 5 күн бұрын
void ProcessOrder(OrderId, IDiscount); readonly record struct OrderId(Guid Value); interface IDiscount { void Apply(OrderId) } class NoDiscount : IDiscount class PercentageDiscount : IDiscount // more discounts...
@holger_p
@holger_p 20 сағат бұрын
Enum item names are used throughout the entire application. For a boolean paramenter you "invent" a new parameter name on each method you are passing it into. And here you could make mistakes. Especially on refactoring, there is no automated "rename all" for case you ever change the meaning of the original value. It's simply type safety, not to call a function(bool isenabled) with function(IsFrozen). With bool the compile would allow it, with two different enums, he wouldn't.
@demetriojunior164
@demetriojunior164 3 күн бұрын
Honestly in this particular case, would be even more valid to question why a [bool applyDiscount], if a [decimal discount] would make so much more sense here. Everytime i'm working on parameters like this i stick to it's original purpose. If i'm using the word "discount" somehow, it becomes so more auto intuitive to use a float point number instead of a boolean, because the word "discound' just tells my brain to think about a number with probability for 2 decimal cases. Also, anytime i have a method with a bool value where the "if true" routine is complex and/or long, i rather to shatter into more than one method.
@rafazieba9982
@rafazieba9982 6 күн бұрын
There are multiple ways you can look at this issue. Boolean blindness is only one of them. It is important. Yesterday I told someone that if they can explain to me what true and what false mean and why true is true and false is false they can use it. Otherwise they have to introduce an enum. The fact that something has only two or three possible values doesn't mean it is a boolean or nullable boolean. The second problem is much deeper. Pattern matching was introduced because people used such constructs not the other way around. If you are writing a switch statement based on type it usually means you did something wrong when you were designing your class/service/application. The proper way to do this is polymorphism and strategy pattern. The same thing applies to methods that have a bool parameter and two branches. Unfortunately with the introduction od dependency injection people forgot what polymorphism is. All this crap about unreadable code etc. The way it is now just use this bool. Write that if. Don't warry about it. The compiler will fix it for you.
@davidklempfner826
@davidklempfner826 4 күн бұрын
I can't believe the article didn't mention the main reason for using enums over bools as params, the fact that you can add an extra value to the enum and it's not a breaking change. You can't do that with a bool.
@holger_p
@holger_p 20 сағат бұрын
By architecture it adds some type-safety. As well as you could add "7 meter + 5 miles = 12 'nonsense'. You could do the same thing on the logical level. You do not "or" combine things, that aren't combinable, you add kind of a unit to the value.
@sergeybenzenko6629
@sergeybenzenko6629 6 күн бұрын
The only justification I can think of is that if you have 2+ boolean parameters, then make them separate enums so you don't mix them up when calling a method.
@Shynobyn
@Shynobyn 4 күн бұрын
Basically big consulting firms put juniors and interns to work with little guidance and no coding standards and at this point Clean Code is basically this minimum set of standards which can help preventing this kind of crap. It isn't that great but it's something. For instance regarding this topic you find functions with a boolean paramater where the two branches are copy pasted anyways, and it's all the same except for a couple lines that change based on the parameter. So at first glance it looks like it would be better to separate this in two functions, until you look closer and realise it's just those 2 lines that change.
@keyser456
@keyser456 6 күн бұрын
It's when people make broad sweeping statements and overgeneralizations that they get themselves into trouble. Heard a new kid that joined our team a few years back confidently declaring relational databases were "too slow". He wanted to build everything with no-sql and document databases because that's what he was taught. It didn't matter that most the senior devs around him could write (and in many cases have written) entire systems against a relational datastore that would run circles around anything he built. Because he heard something from someone, it must be true in his head.
@gppsoftware
@gppsoftware 6 күн бұрын
I came across one of these people once. He tried to tell me that everything I had ever learned and done in the last 30 years of using SQL Server was wrong and that No-sql was the only way forward. I said to him: lets export your data from your No-SQL and import it into a SQL Server database. I will then apply foreign keys and we will see how good your No-Sql is! Needless to say, his business was built on a data that had no integrity and had orphaned data everywhere. My observation is that most organisations that go down the 'No-sql' route do so because No-sql implementations are usually free whereas you have to pay for SQL Server. They then proceed to use No-Sql as a 'substitute RDBMS' and wonder why their data integrity is absolutely shot. To be honest, I have never seen no-sql implemented successfully. Yet some people use them as the foundation of their business! Foundations on sand comes to mind...
@JohnnyCoRuyzo
@JohnnyCoRuyzo 6 күн бұрын
I like to use a option class, and set the properties with boolean parameters. Only if i have multiple booleans on that function, or multiple booleans that will need to be passed thru bigger functions. And the default value will be defined inside the option class.
@mDoThis
@mDoThis 3 күн бұрын
I wanna more clean-code-triggered-Nick :D You should make separate series going through this book!
@VanderScript
@VanderScript 13 сағат бұрын
Alway enjoy your videos, I have my team of developers watch your channel too. Code Cop ones are my favorite.
@Robert-yw5ms
@Robert-yw5ms 6 күн бұрын
Passing booleans is a bigger problem in languages that don't support named arguments. Js/ts is the one that immediately comes to mind. Edit: also it's definitely valid to start with the boolean, evolve to an enum if there are more than 2 options and finally inject the discount as a strategy if that gets too complicated. Refactoring is allowed!
@SfrOschNOR
@SfrOschNOR 6 күн бұрын
I'm a c++ developer and I'm still learning c#, but in c++ I think you should avoid booleans as parameters. If you read Code and see a function call you do not immediately see what true means. But if you use a (scoped) enum with yes and no you can see whats happening more easily. Also it helps creating stronger typing.
@casperhansen826
@casperhansen826 6 күн бұрын
It made sense until enum with yes and no
@ulfjohansen2139
@ulfjohansen2139 5 күн бұрын
There is also the problem that the enum is not guaranteed to have only two values. In fact it could be any number that can be represented by the underlying type
@ingermariejakobsen1335
@ingermariejakobsen1335 6 күн бұрын
Sometimes a method takes multiple booleans as input. In that case it might actually be easier to both call the method and read its code to use an enum (or even a flagged enum) to cover all permutations of the bool. also, never use negated bools. Ever. A bool named NoDiscount or IsError is bad. A value of true should represent goodness or an existing value, not badness or a missing value.
@Kiccsalad2011
@Kiccsalad2011 6 күн бұрын
Just couldn't agree more. Exactly what I think of these short sighted dogmas. And this is one of the most aggressive ones.
@alanthomasgramont
@alanthomasgramont Күн бұрын
I see this in architects all the time especially if they are not writing code daily. They will rip apart your PR without understanding the added work they are adding now and in the future. When you had a dozen sun methods to control its difficult to know their dependencies. Someone coming into your code a year later will need to spend time understanding the order and where in your code that three line method is effecting.
@karolstopinski8350
@karolstopinski8350 6 күн бұрын
This comes down to logical organization of a code. You make a function to combine input parameters and spit out a result. If the result depends not only by some values but also some flags you want to have all that processing done inside that function thus need to have some bools passed to it. That enum looks stupid for a bool. For a bigger group of possible states it makes sense but for just two states no.
@CGX106
@CGX106 6 күн бұрын
I'm already grateful that you're venturing into these dark corners of LinkedIn, so I don't have to.
@ianosgnatiuc
@ianosgnatiuc 6 күн бұрын
That's discount option, which means there might be several kinds of discount. That makes sense if you plan to have more than one kind.
@ThatLuckyKill
@ThatLuckyKill 5 күн бұрын
If you have a single true false operation an boolean is the best, for example IsFlipped. Why implement and enum that uses Flipped and NotFlipped to represent the same. However, if you have to inpute more than one boolean, you could search for different solutions, depending on the use case
@asagiai4965
@asagiai4965 6 күн бұрын
Opinions. 1.) Don't use enum like it is your boolean. Unless you really need to. Here, the person don't want to use boolean so instead he uses enum, but what he does is basically the same thing. 2.) People should stop using function argument they don't really need. Ex. Why does he need an order ID for discount? Maybe if he was modifying an order to give more or less discount then OK. But in this case it doesn't look like it is the purpose of the function. 3.) Enum could have been used much properly here. Also too many enum I think is bad. 4.) Lastly, the code should have good logic flow.
@travisabrahamson8864
@travisabrahamson8864 6 күн бұрын
I agree the bool has a finite list where the enum has an infinite list which potentially creates cognitive problems. The approach should be looked at why do we need a bool parameter and determine are we doing different things or are we doing the same thing with a twist. The other part is does this code need to know about that decision? Such as should I have cases where the discount is calculated differently - Flat, Percentage, based on when its paid such as a 10% discount if paid in 10 days Net on 30? This may indicate I've to simple a concept on Amount Due or on Discount itself.
@davidmartensson273
@davidmartensson273 5 күн бұрын
For the given example its wrong, a single boolean with a good named for the argument is not a problem, as you say, if it more or leas split the internal processing into two completely separate paths, having two methods and lifting the if to the parent is probably better. But one case where sending booleans are bad is if you for some reason have multiple booleans to the same method. In that case I find that having named enums makes it easier to quickly glance at the call and know what the arguments really are, but of cause then you cannot use "none" as a boolean value but rather "AddDicount" and "NoDiscount" or similar. Or if there are multiple booleans, maybe add an options class to send in the parameters. That way you also can set only the parameters you need changing and leave the rest out to use default values. BUT as you mention, the int for orderId is in the context of clean code way way worse :D and especially if you need to send two int values for two different Id's, where swapping the order of them will not cause any compilation error. So replacing that with either an OrderId class, or as mentioned, adding am options or argument class would probably do more to improve the example. I do like most of the Clean Code rules BUT they need to be treated with some common sense, like som much else, they are guidelines to have in mind, not hard binding rules, and the end goal is always to make the code easy to read and maintain, and if a simple boolean is sufficient, why ad another class. Now, if your going to pass this boolean around, maybe through multiple levels of methods or similar, then adding an enum might still be useful since you are no longer dependent on the naming of arguments or variables that might change throughout the path if multiple developers have written different parts, but that is a whole different can of worms ;) For any similar case I prefer the way of Domain Primitives where not only are you avoiding raw data types, but you anything more varied than a boolean, you also can add limits. OrderId's most likely should not be able to be 0 or negative, same with price and quantity, AND you get the type check in the methods for free when using such domain specific classes :)
@donald4nola
@donald4nola 6 күн бұрын
I don’t think this is necessarily about booleans. Anytime there’s a decision early in a method that results in two different paths, it might be easier to maintain if each path was in its own method. That doesn’t change if a two state enum is passed instead of a Boolean.
@tymurgubayev4840
@tymurgubayev4840 5 күн бұрын
when I'm adding a boolean parameter to a method, I found it useful to stop for a moment and consider if it should be an enum, or maybe two methods instead. More often than not I decide to keep the boolean, but sometimes I do choose another option.
@LarryB15
@LarryB15 6 күн бұрын
I get really sick of these rules. Firstly they should never be rules, at the most they should be guidelines. Sometimes it's better to use a single method with a couple of bools, other times it's better to separate the methods. But think, you could separate a function with a single bool into two functions. If you had two bools you would need 4 methods and 3 bools would mean 8 methods. Think of the naming hell, MyMethodWithClause1ButNotClause2 etc. The point is, do what feels right at the time. I would rather write a function, test it and check it in rather than wasting another 15 minutes debating whether my approach is right.
@BenMcCallums
@BenMcCallums 6 күн бұрын
The one thing I would say is that doesn't at all relate to "Boolean blindness" or any of these silly reasons lol is that the enum can be extended over time to support additional cases. So often in our API design sessions we'll change a configuration type bool column on an entity to an enum like FooMode or BarType. Bool can pigeon hole behaviour toggling very quickly.
@JanusChan
@JanusChan 6 күн бұрын
I don't wanna split my order method in 'Orders with Discounts' and 'Order with Discounts' and then need to make a seperate payment calculation method to not have code duplication in both? This does not save me anything and does not make anything more or legible... I could just add one life with an if statement and a boolean..... I totally agree with you here.
@Shenron666
@Shenron666 6 күн бұрын
I never use boolean type, instead I use a a custom implementation to make a stored procedure call for better performance drop if the call is too fast, i add throttling and thread sleep
@markcahalan5698
@markcahalan5698 Күн бұрын
"Clean Code" is for people that don't care about Time or Space And in the case of a dozen two line functions instead of two bigger ones, traceability
@alexanderqwerty
@alexanderqwerty 6 күн бұрын
Thank you man, for trying to stop clean code madness
@_iPilot
@_iPilot 6 күн бұрын
The author has chosen an extremely incorrect example. If there are 2 or 3 booleans and not every combination of them is valid, then it could be a subject for replacement the multiple booleans with a single enum (I personally would prefer a flags enum in such a case).
@0xAC
@0xAC 6 күн бұрын
I think Nick is absolutely correct here. Overall, named parameters are extremely powerful tools in the context of creating readable code. There are other techniques as well, but indeed, just replacing boolean with an enum is not solving anything. In context of Uncle Bob, I think it is interpretation problem. I don't think he meant that boolean should not be passed to a method ever but that often it is better idea not to. On github there is a massive number of examples of wrong methods design. The real problem is absolutely different. People hear an advise and bilindly apply it without understanding the context or purpose.
@rogerr4469
@rogerr4469 2 күн бұрын
Imho, the example provided is confusing and not suitable for discussing whether a boolean parameter is a good or bad practice. A ProcessOrder method should take an Order object as a parameter, with 'discount' as a property of that object.
@alanschmitt9865
@alanschmitt9865 6 күн бұрын
That rocket emoji is a dead giveaway for Bing’s GPT implementation
@Nojo524
@Nojo524 6 күн бұрын
Boolean as a parameter is ok. Just don’t return a boolean from a method. It makes the method not clear on what that value is. Return an enum is the better choice.
@gilesmiles8458
@gilesmiles8458 Күн бұрын
The issue with booleans is that they're often just passed as-is without clarification, which makes the calling code harder to read. Also, even if the parameter is well named, the intention isn't always clear. If you had a boolean called orderedPepperoniPizza, what is false here? Ordered fries? Ordered nothing? Ordered some other pizza? Enums just make this clearer from the get-go if they're well named. Also, arbitrarily hard coding the number of options to 2 makes little sense (see 0, 1, many testing). Coding with enums future proofs the code. And no, this isn't WET code, you can just add the cases as they appear. And even if they don't, this makes for far more readable code in my view - YMMV. But this isn't something I'd insist was changed in a code review. I think it is important to embrace different styles. Sometimes it is better to use carrot than stick. Point out the consequences of the design decision and make sure the developer is at least thinking about the implications of their decision.
@Ilix42
@Ilix42 6 күн бұрын
The reactions on LinkedIn aren’t a valid way to judge how much support a post is getting since there are no negative reactions. His post could have had many times as many down votes as it had positive reactions, if the option existed. It’s a great example of the problem of not having the ability to give critical feedback easily.
@andrewgr144
@andrewgr144 6 күн бұрын
The majority of engineering time for almost any successful project is spent in maintenance and upgrades, not in the initial implementation. Whenever you use an enum, you introduce the possibility that a different programmer years from now will add a new value. Depending on the language you're using, this could cause compile-time failures for functions that don't explicitly handle this new value, or it could not even bother to issue a warning, or anything in between. This is not an argument against using enums; it's an observation that thoughtful programmers will keep in mind when creating and using enums. If the value of a parameter is literally always true or false, using a bool for the parameter type should be correct; if it's not correct, there's a fundamental problem with whatever language you're using.
@kevinison3740
@kevinison3740 6 күн бұрын
Clean code depends on the eye of the beholder sometimes... Not sure I completely agree with all this. Especially after about 40 plus years.... But it does give me something to think about, Thanks Nick!!
@NickTheCodeMechanic
@NickTheCodeMechanic 6 күн бұрын
I wish people would stop doing dumb things in C#. But if they did, I wouldn't be able to charge for fixing their screwups :)
@holger_p
@holger_p 21 сағат бұрын
It's not dumb. Sometimes it's old, things that were not possible 20 years ago. Or it's quick and dirty, they had to meet a deadline within 4 hours, and then you minimize typing. That's a topic of renovation in a chill moment.
@NickTheCodeMechanic
@NickTheCodeMechanic 16 сағат бұрын
@@holger_p talking about the bools and small mistakes that shouldn't be, regardless of .net version.
@tedwagner5018
@tedwagner5018 6 күн бұрын
The problem with this isnt the bool it is that it hides the discount applied. The discount is hard coded or passed as a property which makes it hard to ubderstand what discount is applied when the function is called.Use an enum and assign discount values to use then pass the enum. enum Discount{ None=0, FifteenPercent=15, ThirtyPercent=30 }
@andrewgr144
@andrewgr144 6 күн бұрын
It all depends on what the underlying business logic is. For some models, what you suggest would be correct; for others, it wouldn't be. The discount needs to be calculated somewhere, and if the business logic allows for it, ideally it would only ever be calculated at a single point in the code. So if the example function is called from more than one location, you'd like the function itself to calculate the applicable discount (retrieving it from a database, extracting it using the order number, searching through a list of current coupons and discount codes, or whatever). Presumably the function would normally be called with 'true', but since some coupons and discount codes require customers to supply information like their email address to companies they don't necessarily trust, you might want to call it with 'false' if the customer selects a checkbox saying, "Don't use 3rd party coupons", or something similar-- obviously I could refine the example and make it tighter and more realistic given some effort, but I think the example as-written should be enough to convey the idea.
@tofu1687
@tofu1687 5 күн бұрын
You're about to debunk DDD : don't use int for orderId - create a value type OrderId
@matthewsheeran
@matthewsheeran 6 күн бұрын
Nah: if it's always gonna be binary, it's a boolean! Enum here breaks the less code is better code golden rule whilst being equally maintainable though not as extensible, BUT, if it's always going to be binary, then it's a boolean, IMO!
@diadetediotedio6918
@diadetediotedio6918 6 күн бұрын
> Enum here breaks the less code is better code golden rule This is not a "golden rule", it is a general and specific rule applied to very specific contexts. You cannot approach domain objects or newtypes if you follow this to the maximum extent, you would also not use any statically typed language in that same matter (as dynamic languages objectivelly need to achieve the "same" things). If something is binary it does not mean it is a boolean, a boolean has a pretty objective description: to be true or to be false, it is reasonable to use when you need to describe something that can be either true or false, but not that has 2 possible states, this way of thinking fastly turns into extreme primitive obsession.
@avisian8063
@avisian8063 6 күн бұрын
If its always binary use a byte 😜
@barionlp
@barionlp 6 күн бұрын
„Absolute Rules are the last refuge of the incompetent“
@ando_rei
@ando_rei 5 күн бұрын
One way most languages allow for to overcome this isn't even discussed: why not extract the two paths the bool stands for into methods and pass the appropriate method to processOrder? This way you don't have a bool and you don't have Uncle Bob's code doubling. If the methods are small enough most compilers would inline them anyway, I guess 🤷‍♂️
@rafaelpereiradias2567
@rafaelpereiradias2567 6 күн бұрын
More than 1 option to decide? Enum, 2 or less, bool. Simple. Bool uses 1byte and enum uses 4bytes, so it works like an int, but the gain it's soooooooooo negligible, that doesn't matter if you use bool or enum.
@hunazazel
@hunazazel 5 күн бұрын
This video I don't agree with. I've had the unpleasant experience of seeing method calls such as CreateOrder(117, true, true, false). Yes, I can hover over the bool in my IDE and read the param name, I can add the name to the method call (and fight my IDE telling me that I absolutely don't need it because I am just passing positional params in the order they ar declared in, so why do I pollute the call with their names), or I can extract a parameter object that contains those named bool as init-only props, construct that, but that's also a mess. So instead I can actually create the enums, and instead of CreateOrder(117, true, true, false), I can have something like CreateOrder(117, Discount.Apply, Shipping.Expedited, Insurence.None), that certainly is easier to read.
@ab1ray
@ab1ray 6 күн бұрын
In terms of discount, what would be better to pass is an Order object with a Discount % property. 0 == no discount.
@gweltazlemartret6760
@gweltazlemartret6760 3 күн бұрын
5:24 "bool can only have two values" -albeit a bit false (because, you know, _null_ ), I've read api concern about having an input for buying a ticket at discount, then with vip mode, then with another thing bloated inside. So to keep the method simple, just use an enum and have the internals of the method do the routing. BUUUT if you have the need to expand the enum, you'll have to reship the api exposing it, and the consumers will have to update aswell, exactly same as an api change -because it is. At the end of the day, it’s not different than having multiple dedicated bools, and/or dedicated methods. So, *the code smell* could actually lie in the *enum* side.
@sm5574
@sm5574 6 күн бұрын
Instead of having an addDiscount boolean parameter, I would contend that a discountValue decimal parameter is a better option.
@rick_info_dev_pyt
@rick_info_dev_pyt 15 сағат бұрын
This is a logical or business concern. At the begining the value just takes 2 possible state (true or false), but sometimes at the end, we may find that the concept that this value bears, is not a binary thing, what may lead to make things evolve towards an enum. Example : bool roomIsReserved may evolve into : enum RoomState { Available, Reserved, UnderReconstruction, ...}, some exclusive states, and may be in that case this could even evolve into a Room Entity, instead of enum. So going straight at the begining to an enum, maybe overingeneering, except if there are great chances to evolve to more than 2 states. Anyway, SYSTEMATICALLY replacing bool params by enum, doesn't make sense in itself.
@marko5734
@marko5734 6 күн бұрын
I think it depends on the use case. If there isn't too much responsibility on the boolean it's fine. If you have a bool and is just small part of the logic it's fine. But it may be wrong choise if it have too much influence on the whole. For example let's say there are many methods and method a is calling method b just to get some info and continue the long chain it's totally fine. Introducing enum here isn't changing anything in this context. No benefit from that.. This example where enum is better choise compared to bool could be useful for flexibility in complex object creation. In this case simple yes or no may not give enough context especially if there are multiple factors involved which influence the overall result. It can especially be useful for respecting ocp principle. Just my opinion...
@klocugh12
@klocugh12 6 күн бұрын
Use enums instead of bools mainly if you suspect possibility of adding more cases in the future.
@ВладимирМакайда-м9т
@ВладимирМакайда-м9т 6 күн бұрын
This advice is as wrong as the original. I've seen projects with hundreds of interfaces, methods, enums that were easily thrown away. When I asked why, I got the answer, it will be useful in the future. And they dragged this garbage from version to version, and the future never came.
@klocugh12
@klocugh12 6 күн бұрын
@@ВладимирМакайда-м9т No. It means judgement a programmer made was wrong, not that advice in general is wrong - if anything, it may be risky instead. It's not a big deal either way - code won't break, run 10x slower or turn into spaghetti just bc it's enum and not bool passed lmao.
@ВладимирМакайда-м9т
@ВладимирМакайда-м9т 6 күн бұрын
@@klocugh12 enum requires maintenance
@holger_p
@holger_p 21 сағат бұрын
@@klocugh12 the "break" is to come on future changes, when you missunderstand the meaning of variables. You are right, not a big deal, but more then nothing. The reasons not to do it are things like "never touch a running system" and "we won't pay for this".
@ErazerPT
@ErazerPT 6 күн бұрын
You know... as time goes by, i feel less and less "forgiving" when it comes to "coding religion". Yes, there are some BadThingsTM, but this is surely not one, it's just someones "religious issue".
@krss6256
@krss6256 6 күн бұрын
That enum suggestion makes a little bit more sense if you have more booleans than just one and a specific logic of the method that depends on all of them at once. But in that case selecting booleans in the first place was a really bad choice already.
Stop Using FirstOrDefault in .NET! | Code Cop #021
12:54
Nick Chapsas
Рет қаралды 78 М.
The New Option and Result Types of C#
15:05
Nick Chapsas
Рет қаралды 70 М.
规则,在门里生存,出来~死亡
00:33
落魄的王子
Рет қаралды 26 МЛН
Как мы играем в игры 😂
00:20
МЯТНАЯ ФАНТА
Рет қаралды 3,3 МЛН
🍉😋 #shorts
00:24
Денис Кукояка
Рет қаралды 3,7 МЛН
The Alternative to Deleting Data in .NET
11:11
Nick Chapsas
Рет қаралды 31 М.
Testing in .NET is About to Change
12:54
Nick Chapsas
Рет қаралды 68 М.
My 10 “Clean” Code Principles (Start These Now)
15:12
Conner Ardman
Рет қаралды 233 М.
Microservices are Technical Debt
31:59
NeetCodeIO
Рет қаралды 403 М.
Stop using std::vector wrong
23:14
The Cherno
Рет қаралды 75 М.
"Stop Using Async Await in .NET to Save Threads" | Code Cop #018
14:05
The Value of Source Code
17:46
Philomatics
Рет қаралды 51 М.
Stop Using IEnumerable The Wrong Way in .NET! | Code Cop #019
10:10
The Logging Everyone Should Be Using in .NET
15:34
Nick Chapsas
Рет қаралды 71 М.
ChatGPT-o1 Created A Programming Language...
19:45
Conner Ardman
Рет қаралды 54 М.
规则,在门里生存,出来~死亡
00:33
落魄的王子
Рет қаралды 26 МЛН