Replace Conditional With Polymorphism & Primitive Obsession | Code Walks 045

  Рет қаралды 27,685

Christopher Okhravi

Christopher Okhravi

Күн бұрын

Can ALL conditionals be replaced by polymorphism?
► Refactoring, by Martin Fowler
amzn.to/2oI9ikx
► The 1st chapter can be read on Google Books
books.google.se/books?id=HmrD...
► Sandi Metz on programming without "if"
• RailsConf 2015 - Nothi...
GEAR USED
► CAMERA: Canon 70D amzn.to/29wR8wG
► LENS: Canon 10-18mm amzn.to/29srabL
► TRIPOD: JOBY Gorillapod Zoom amzn.to/29AdkHT

Пікірлер: 54
@MrBatocko93
@MrBatocko93 Жыл бұрын
In JS, for example, we can declare a map that holds the 'logical program paths' as keys and behaviours as values (objects or plain function) and a field that does a default behaviour of some sorts. That construct is something i use a lot and it makes the code super readable.
@maximillianeo
@maximillianeo 4 жыл бұрын
Nice concept of walk talk !!
@ChristopherOkhravi
@ChristopherOkhravi 4 жыл бұрын
Appreciated.
@pietro1901
@pietro1901 2 жыл бұрын
This remembers me the oposite of primitive obssession, complex obsession, when you replace primitives when them are required
@jeffruan7701
@jeffruan7701 5 жыл бұрын
This is a perfect example of no-primitive obsession.
@smilebot484
@smilebot484 7 жыл бұрын
Your factories will likely need conditional logic. Polymorphism masks conditionals, but at some level in the code they need to be there seems to me.
@ChristopherOkhravi
@ChristopherOkhravi 7 жыл бұрын
Well put. I agree. Thanks for watching! :)
@josephwalters3379
@josephwalters3379 4 жыл бұрын
The point is to isolate the logic. Of course we have to have ifs! It’s how we control the paths of the program. But the goal is to isolate ifs that are “silently” duplicated in other places in the code. Where should that control live? In 1 place or in 5? What happens if there is a bug in 1 of the ifs? Do you need to change all 5? Or just the one in the factory...
@SpencerDavis2000
@SpencerDavis2000 4 жыл бұрын
thanks for reminding me to get this book. I remember seeing him at SCNA 2013. going to relearn this stuff again
@mirianadimitrova2112
@mirianadimitrova2112 4 жыл бұрын
This channel gives me life ❤️❤️❤️
@ChristopherOkhravi
@ChristopherOkhravi 4 жыл бұрын
❤️💪💫
@GokulKartha
@GokulKartha 7 жыл бұрын
Hei Christopher, It would be great to see you explaining these with the white board :) , Lot of Background distractions ..
@ChristopherOkhravi
@ChristopherOkhravi 7 жыл бұрын
Excellent suggestion! Thank you very much. There's a poll for patrons (patreon.com/christopherokhravi) in case you're interested in influencing what the next whiteboard series will be :) I will first focus on finishing the Design Patterns series, but after that I will indeed jump into a new series. And I am indeed thinking about doing the different refactorings listed by Martin Fowler in his book Refactoring (amzn.to/2qDVaNv). But I thank you very much for letting me know that it would be interesting :) Thanks for watching! :)
@paragkadam2169
@paragkadam2169 2 жыл бұрын
Awesome video
@mattborisov
@mattborisov 6 жыл бұрын
I really like the way you explain things! :)
@erictsang0
@erictsang0 6 жыл бұрын
The codebase at my work really needs to watch this video
@olivermeyer3963
@olivermeyer3963 4 жыл бұрын
Hi, I would go 1 step ahead, u just have to use a hashtable, put your primitives in it and get the right object/interface/class from it. so you are able to replace all conditionals with hashtables, even when dealing with primitives far on the outer edge of your application.
@ievgeniiiablonsky1161
@ievgeniiiablonsky1161 7 жыл бұрын
3:25 "Cats and Dogs override the speak method from Animal" Aren't we violating Liskov Substitution Principle here? Can you please explain it?
@ChristopherOkhravi
@ChristopherOkhravi 7 жыл бұрын
Very important question. However I'm not sure exactly how you mean, so please do feel free to expand. I find that LSP often becomes of question of semantics. While describing math LSP is often obvious but when we describe things such as animals it becomes very context dependent. As in that it depends on what the "expected behaviour" of the application is, or in other words, what we want the application to do. If all animals can speak (given the context of the application) and if Cats and Dogs speak in a way that is not outside the boundaries of expected animal speaking behaviour, then it should not be a violation of LSP. But again, given the lack of context, many interpretations are possible here so yours may be just as valid as mine :)
@ievgeniiiablonsky1161
@ievgeniiiablonsky1161 7 жыл бұрын
Thank you for your explanation. I really like your videos and I am literally learning from them. I am creating a cards with what you are talking in videos and learn them using Anki. I also very like what Uncle Bob are talking about, and I want to use his advises. I want getting better in my field. Maybe you can suggest me something, some books that you think is very important, videos, cources, some ways to learn more effectivly? I am iOS developer, workingwith Swift. Now I am reading Code Complete and Working effectively with legacy code, next is Clean code and Refactoring (from one of your videos), also new ones in que are structure and interpretation of computer programs and structured programming book (Uncle Bob's must read). Thank you for what you are doing.
@ChristopherOkhravi
@ChristopherOkhravi 7 жыл бұрын
Cool thing this Anki. Didn't know that service :) Excellent question about books. Beyond the ones you mentioned. I've heard great things about "Practical Object-Oriented Design in Ruby", written by Sandi Metz who I greatly respect due to some great talks she's done that are posted on KZbin. I haven't read it but it's next on my list. Your question however makes me think that I should compile a list of books that I appreciate and post it on my website. I'll comment here when it's up. Thank you again for your kind words. It's highly encouraging.
@perfectketchup
@perfectketchup 3 жыл бұрын
what I'm struggling to figure out is many of this strategies doesn't fit the volatility of reality. Suppose you made perfect polymorphism to hide all your conditionals. What happens when a request of huge extension comes along? you have to be a god to satisfy the reusability on feature creeps. such design requires redesign on harsh requests.
@ahmadbaderkhan598
@ahmadbaderkhan598 2 жыл бұрын
well no , in reality the entire point is not to hide conditionals , but reduce conditionals wherever possible . The reasons for that is readability . i usually prefer to read code that's less branched . furthermore making too many branches in your code / conditions makes your test very bloated and difficult . your function / object is not discreet anymore . again , switch stmts , ifs and whatever all have their place in your code and usually that's centered around things better suited for this for either performance reasons , or the fact that it's not something that needs to be abstracted or modeled to a separate discreet object .
@nicholasdecock6557
@nicholasdecock6557 Ай бұрын
Can we abstract a conditional in a Interface “Evaluate”?
@albinbergstrand9416
@albinbergstrand9416 5 жыл бұрын
im trying to get into C++ (im mainly a 3D artist) so this is way beyond but perhaps i will one day. subbed :D
@lincolnsand5127
@lincolnsand5127 3 жыл бұрын
Do not follow the advice in this video if you're using C++. You should limit any runtime polymorphism via inheritence that exists in your code if using C++. The advice in this video only applies to high level languages.
@joshuamanton
@joshuamanton 4 жыл бұрын
There is nothing wrong with ifs and switches. Use whatever helps you get the task done while being simple to change if/when requirements change. Using objects everywhere makes your code very resistant to change, turning a simple refactor into a huge ordeal where you need to throw everything out and start from scratch. This obsession with design patterns isn't based in reality and doesn't help you actually do anything except write more code than you need to to solve a particular problem.
@josephwalters3379
@josephwalters3379 4 жыл бұрын
There is a point where software needs additional abstractions. Not every program needs them of course, but it’s understanding WHEN to use design patterns and do proper refactoring that matters. Requirements change, software changes. What you want to do is limit how much the code changes and/or how often. There IS such a thing as over-design, blindly following something because it’s “good practice” is not what anyone should do. Regarding a simple refactor, changing an if statement is NOT a refactoring of your code. Refactorings have names and are generally tied to deeper problems within a larger codebase. Also the note with the specific refactoring mentioned here - the goal isn’t to replace ALL ifs that would be insane and would definitely make it resistant to change. It’s about identifying logic that is being DUPLICATED “silently” in a way. If you have 5 ifs that check if something is positive, then MAYBE that should be refactored, it’s not that it must. It’s just a code smell, just because it may smell it’s not bad (yet). And if you code will never change and you know that, then it should just be left alone.
@davidspencer3726
@davidspencer3726 Күн бұрын
Tim Corey has quite a pragmatic view on patterns: only use them to simplify your code.
@yktoledo
@yktoledo 3 жыл бұрын
Most of the time I hear how convenient is polymorphism for those scenarios, but sometime, is kind of inevitable, I have to create an object depending on experiment featureflag, where the flag is primitive, is not an object that I can implement anything, is just a String or Integer, for those cases I think is inevitable.
@simplepaperclips604
@simplepaperclips604 3 жыл бұрын
All of the examples I have found that explain replacing conditionals with polymorphism have a single switch-case that is replaced by a single method in the abstract class or interface, and then the method is implemented by each concrete class. How do we avoid violating the single responsibility principle when we have many different methods that depend on the same 'type' field of the object, and are using some kind of conditional? If we refactor each of these methods to be part of the abstract class or interface then the resulting derived classes would end up doing a lot of things that have nothing to do with each other. For example we could end up with an object which has a method for generating a view component and a method for implementing some unrelated business logic (both of the methods previously depended on the type field). We could have many different kinds of methods end up in the derived classes that we have defined. I'm 100% sure I'm missing some information here which why I can't figure this out, and any answers would be greatly appreciated.
@avimehenwal
@avimehenwal 3 жыл бұрын
I am a novice wannabe programmer, so pardon if my question is too generic. Is there any example(s) code which makes the case that Polymorphic objects are better (in terms of redability, maintainability and testability) than using conditionals? Asking this as I haven't seen anyone using Polymorphic objects instead of conditionals and would really appreciate some example/reference code to understand it.
@davidmataviejo3313
@davidmataviejo3313 2 жыл бұрын
Search for strategy pattern. The strategy pattern is about using Polymorphic objects instead of concrete clases. But still if you are using dependency injection you will need to use the factory pattern to return the correct concrete class using if or switch statements
@alexdavies4121
@alexdavies4121 2 жыл бұрын
So what if for example you have a list of notification objects from a service and the notification object contains an enum which would tell the front end what actions a user can perform based on that enum. How can that be polymorphed? In this example the backend does not do anything with the enum except as a way label or classify a notification type.
@StevenMartinGuitar
@StevenMartinGuitar 2 жыл бұрын
Thats pretty much how event systems work, no?
@RemiStardust
@RemiStardust 6 жыл бұрын
0:53 "So conditionals are switch statements, if-statements etc. etc." - What do you mean, etc. etc.? I can't think of any other conditionals (in Java).
@russelljones9540
@russelljones9540 5 жыл бұрын
Ternary operators are conditionals, so are OR (||) statements.
@andreagiraldomdphd.8376
@andreagiraldomdphd.8376 6 жыл бұрын
I should have said IFS without apostrophe! One can use apostrophe with special plural or rather with SINGULAR numbers (5’s) and letters (d’s). Love. A
@ChristopherOkhravi
@ChristopherOkhravi 6 жыл бұрын
Ah dang! Of course. Thanks for correcting me! Also, thanks for watching :) :)
@andreagiraldomdphd.8376
@andreagiraldomdphd.8376 6 жыл бұрын
Christopher Okhravi Ah DANG ! Really nice exclamation, I have never heard before. I do like it and will use that. Thank you. Andrea from Venice, Italy
@namangrover1989
@namangrover1989 4 жыл бұрын
Great work Christopher. I've fallen in love with you. I wish I was this cool. :( Anyway, I have a question for you: Let's say every condition is replaced with polymorphism, but we need to iterate over each behaviour right? void driver() { if (Cond1) { do_some_work; } else if (Cond2) { do_some_other_work; } } ==> interface ICondition { boolean satisfies(); void doWork() } List conditions = [new Cond1(), new Cond2()]; //Cond1, cond2 implements ICondition for (ICondition condition : conditions) { if (condtion.satifies()) condtion.doWork(); } Is this what you mean? if this is the case, we are violating Dependency inversion principle in the driver function.
@zerosandones7547
@zerosandones7547 3 жыл бұрын
any code examples for this?
@oscardiaz9170
@oscardiaz9170 4 жыл бұрын
Are you going to keep making videos?
@shenth27
@shenth27 3 жыл бұрын
Good explanation. I hope you won't get hit by a vehicle walking and talking to a camera.
@cyantulip
@cyantulip 6 жыл бұрын
Could you give a formal definition of obsession? No, really. I have OCD. I *must* have a formal definition! LOL
@tomwimmenhove4652
@tomwimmenhove4652 4 жыл бұрын
I love your videos, but in this instance I have to disagree. It seems to me that, if you go out of your way to 'hide' conditionals, you're basically obfuscating your code. This can't do much good for code clarity. I'm sure there are many instances where replacing conditionals with polymorphism is a good idea, but I don't think there is something inherently bad, dirty or smelly about them. It sounds a little like the pendulum having swung a bit too far in the opposite direction. ("Just because we can doesn't mean we should") :)
@Zayelion
@Zayelion 3 жыл бұрын
This is my instinctive understanding too.
@chrisjust7445
@chrisjust7445 7 жыл бұрын
This doesn't make sense. Your classes might be nice and polymorphic, but all classes are made of primitives, or the classes contained in those classes are made of primitives; and you almost always need to do some kind of comparisons of those primitives like: if (myString == null || myString.Length == 0) { DoSomething(); } else { DoSomethingElse(); }
@ChristopherOkhravi
@ChristopherOkhravi 7 жыл бұрын
This comment is on point! I completely agree and find it an extremely fascinating concept. What you are saying is very similar to what I was trying to convey. Unless I'm misunderstanding of course :) At the "edge" of most applications you necessarily have to make use of conditionals because most (useful) applications necessitate interaction with primitives of some sort. In other words, it seems to me that if we apply "replace conditional with polymorphism" extremely aggressively, we should be able to eliminate all conditionals except a few that, even in theory, are impossible to eliminate because the requirements demand interfacing with primitives by definition. Building a system in such a way would probably also make extensive use of the maxim "Tell Don't Ask" since we would have to avoid asking objects for primitive information and instead polymorphically tell them what to do. However... I'm not saying that going this far is a good idea :) I have not tried this enough to form my opinion on the subject. But I find it an extremely fascinating idea, and suspect that it potentially could lead to very maintainable design. Thank you again for your insightful comment!
@russelljones9540
@russelljones9540 5 жыл бұрын
The speaker is not saying that you never have to do the kind of conditional checks that you suggest, but that where possible you do the check ONCE as the data enters your application from outside, and from that check you create an appropriate polymorophic object that knows how to behave later in the code, so you never have to do the check a second time. In your example, if we change myString to userCommentTxt, which we will assume is an optional comment box that a user filling in a form on your app may fill in if they want, then as that form is submitted you can put: userCommentBlank = (userCommentTxt == null || userCommentTxt.Length == 0) userComment = userCommentBlank ? (new nullComment) : (new comment) The correct object is now created so later in your code you can just call whatever methods are on userComment without checking if it actually contains anything, e.g. listofCommentsAsHTML = allComments.map(comment => comment.toHTML).join(' ') It keeps the later code very clean because the conditional is done and out of the way.
@crownsword8045
@crownsword8045 4 жыл бұрын
@@russelljones9540 thanks russell I didn't catch that part of the motivation of why i would want or need to use polymorphism instead of conditionals. Now with your clarification it makes so much sense and I can really internalize the lesson!
@kokoloism
@kokoloism 6 жыл бұрын
0:54 lol
@ChristopherOkhravi
@ChristopherOkhravi 6 жыл бұрын
?
@kokoloism
@kokoloism 6 жыл бұрын
At some point your head was drenched in the dark wood background and it looks like your have more hair. No offense, and keep up the good work. I enjoy your videos.
Emergence Necessitates Mocking | Code Walks 044
4:30
Christopher Okhravi
Рет қаралды 1,3 М.
Factory Method Pattern - Design Patterns (ep 4)
27:21
Christopher Okhravi
Рет қаралды 530 М.
Balloon Pop Racing Is INTENSE!!!
01:00
A4
Рет қаралды 17 МЛН
it takes two to tango 💃🏻🕺🏻
00:18
Zach King
Рет қаралды 20 МЛН
Follow @karina-kola please 🙏🥺
00:21
Andrey Grechka
Рет қаралды 22 МЛН
Последний Закат Кота Макса...
00:21
Глеб Рандалайнен
Рет қаралды 4 МЛН
Downcasting Is A Code Smell | Code Walks 043
6:58
Christopher Okhravi
Рет қаралды 6 М.
Primitive Obsession | Code Walks 055
10:45
Christopher Okhravi
Рет қаралды 7 М.
5 Design Patterns Every Engineer Should Know
11:51
Traversy Media
Рет қаралды 931 М.
Полиморфизм ломает твой код
9:45
ExtremeCode
Рет қаралды 225 М.
Functions vs Classes: When to Use Which and Why?
10:49
ArjanCodes
Рет қаралды 137 М.
Adapter Pattern - Design Patterns (ep 8)
26:36
Christopher Okhravi
Рет қаралды 236 М.
The Only Time You Should Use Polymorphism
13:55
Christopher Okhravi
Рет қаралды 85 М.
Dependency Inversion - how, what, why? (examples in C#) | Code Walks 004
9:49
Decorator Pattern - Design Patterns (ep 3)
54:35
Christopher Okhravi
Рет қаралды 471 М.
Command Pattern - Design Patterns (ep 7)
39:12
Christopher Okhravi
Рет қаралды 262 М.
Balloon Pop Racing Is INTENSE!!!
01:00
A4
Рет қаралды 17 МЛН