Code Refactoring 5

[ad_1]
Code is Here:

In this part of the code refactoring tutorial, I will show you how to replace a constructor with a factory method in 2 code examples.

I also received a challenge from one of you guys that I will solve. The challenge involves how to create a singleton factory method. It sounds more complicated than it is, but by watching this you’ll learn a lot.


Posted

in

by

Tags:

Comments

44 responses to “Code Refactoring 5”

  1. Bhanu Bandaru Avatar

    The solution seems specific to java language as it uses reflection. How would you solve it using c++. C++ has no reflection, I think.

  2. Vitalii Dmitriev Avatar

    Well, in case of 6:30 I think that the switch/case statement is much better, than using a reflection.

    The first issue (younik1 has already met this issue) is that this approach makes it really easy to make a hardly understandable reasons of errors because of just a simple typo. There is an option: use constants instead, or just pass SomeCustomer.class.getSimpleName() as an argument to the getCustomer() method , but it is a workaround and the code will be really long.

    The second issue is that if you will obfuscate and/or shrink your code (e.g. using proguard, which is common for Android Developers), the solution with reflection will be just broken, because as a parameter will be given a string with the originam class' name, but the shrinked class can be called something like AAA, or QQZ.

    The third issue is that the switch/case will win performance, as the reflection operations are quite expensive (and super expensive for Android).

    The fourth issue: reflection option is really less readable, than the switch/case. When you see switch (someVar): case coneType: return new OneClass(); break; case secondType: return new SecondClass(); it is actually simple to understand as it is obvious.
    When you see things like newInstance() it makes you think: why he is using reflection? What will returned? And, which is more problematic, you have to find ALL Customer2's children to understand all options.

    The fifth issue, the minor one: casting is always ugly (hi, findViewById()!) ๐Ÿ™‚

    Anyway, thanks for videos.

  3. Paul Girard Avatar

    You rock, you rule

  4. Vikas K Avatar

    Thank you for making these great videos.

  5. younik1 Avatar

    Hi Derek. Your tutorials are amazing. However I was struggling with Customer2.java with return (Customer2) Class.forName(custName).newInstance(); which when calling through: Customer2 goodCustomer = customerFactory.getCustomer("Premier"); it never returned the desired values. Instead it continuasly gave me: "Exception in thread "main" java.lang.IllegalArgumentException: Invalid Customer Type". After many hourse I ended finding the issue. My code is created with: "package refactor5" so I fixed it with : Customer2 goodCustomer = customerFactory.getCustomer("refactor5.Premier");
    It works perfect now! I'll leave this incase someone else has a similar issue.

  6. TheiLame Avatar

    11:19 isnt that kind of duplicate code? could there have been also a shorter way? Say perhaps handling them all in one class? Im a beginner programmer but ive always told not to use copy paste ๐Ÿ˜€

  7. ร–zgรผr AKPINAR Avatar

    Well, Hello internet. I have been watching, idon't know, 898123. video of yours and now I am repeating it every time when a video starts.

  8. cry sis Avatar

    This guys is amazing. These are by FAR the best programming online tutorial. Tank you so much i will me always in your debet. I am a software architect student and this helps me a lot. Is there a book where you take those problems or is it you personnal experience ?

  9. swapyish Avatar

    did not understand refiection part at all. Can you explain. Do you have good tutorials for java reflection.

  10. juicef Avatar

    Do you realize that the Singletons enforces conditionals (within the "getInstance"-method)? According to the problem statement, your code should not be accepted. Not meant as an offence, just stating the problem ๐Ÿ˜‰ Love your series by the way. Keep them going ๐Ÿ˜€

  11. souleater9189 Avatar

    following in line with your funny names… then shouldn't the silver guy be Ray Kroc? ๐Ÿ™‚

    Edit: nvm… commented while vid was going. should've been more patient.

  12. Sam Bolton Avatar

    After watching the video and thinking about the problem and how you solved it. Based on the criteria given in the challenge, and I'm not saying it's good code, but couldn't you also flip the solution you did, so that the medal classes were singleton's which held a reference to an athlete instead? That way no athlete could be assigned to that medal again. Unless if I'm missing part of the problem.

  13. blake martin Avatar

    I guess I didn't understand the conditional part. I thought that meant that you couldn't use if statements at all, which you did.

  14. Ahmet ลžen Avatar

    I am using same exact code but it is giving me exception in both (Customer2 and Athlete) projects. Any Idea?ย 

  15. aysikl Avatar

    nooo ! :/ … you dropped an R … ๐Ÿ™ … :p

    (refactor/refractor ; fractal stuffs -> refractor = soundscool :p)

  16. Rob L Avatar

    You have so many tutorials I don't know where to start!!!… DEREK F'ing BANAS is the man

  17. Derek Banas Avatar

    Thank you ๐Ÿ™‚ I hope to cover C# soon

  18. saurabh chawla Avatar

    Thanks Derek,

    This is great. Can we have these videos for C#.net too.

  19. Hard Yakka Programmer Avatar

    Thanks Derek,
    I will definitely work that out. (my bad) last time, I just used one of those sleep commands to fix it up a dodgy way. ๐Ÿ™‚

  20. Derek Banas Avatar

    Hi, Race conditions occur when conditions for a thread to continue are based on changes that another thread makes. I have found if you use locks that this problem is eliminated in most situations.

  21. Hard Yakka Programmer Avatar

    Hi Derek,

    Thanks for a bunch of wonderful tutorials. While using Singleton on a multi-threaded (object oriented like Java, C# or C++11 or whatever) application, what would be the best way to avoid the race condition? Last time I was in a similar problem, sometimes every single thread waits for each other and creates a massive dead lock.

  22. ๅคขใฎใŸใ‚ใซ Avatar

    im lost bcs of the reflection, i don't know reflection in c# that well. ((

  23. C S Hayes Avatar

    shouldn't the 'Ray Croc' gold winner supersede the original 'Dave Thomas' gold winner where both goldWinner and goldWinnerNew would both return 'Ray Croc'?

  24. Derek Banas Avatar

    Reflection is almost never a good idea, but for the challenge I thought it would make things more interesting. Yes in these tutorials I have the bad habit of not properly handling exceptions. It is a video tutorial habit of mine and not a real world habit. I'm glad you found it interesting ๐Ÿ™‚

  25. rockYhre Avatar

    Awesome video as ever. But is use of Reflection really the usual case in factory pattern?

    Also, maybe next time you shouldn't catch Exception just to throw new more specific exception. Not good practice.

    Thanks for the video!

  26. Derek Banas Avatar

    Thank you very much ๐Ÿ™‚ My original goal was to provide skills that would help people get a job. I'm very happy that I was able to help you down that path. I wish you the best with your new job!

  27. Alon Minski Avatar

    Brilliant stuff.
    Derek, I've been going over your various java tutorial playlists for quite some time now. Each one is jam packed with useful information.
    I'm about to start my first job as an android developer (and programmer in general) and basically, with the knowledge I acquired from you here, I can safely say you had A LOT to do in me getting my first job. Thank you so much and keep up your amazing work here! ๐Ÿ™‚

  28. Derek Banas Avatar

    Thank you ๐Ÿ™‚

  29. megarocky Avatar

    This was a great tutorial

  30. Mauricio Jorge Cordeiro Garrido Avatar

    3rd- Reflection is used when you dont have access to the source code of other classes, and this classes can give you what you want. Reflection is always better avoid, because java is Static type-checking.

    4th- I want to say thank you for your videos with a lot of quality and all for free. Really thanks.

    Really keep going helping people and getting education for free ๐Ÿ™‚ .

  31. Mauricio Jorge Cordeiro Garrido Avatar

    Hello,
    1st- I want to say thank you for your videos with a lot of quality and all for free. Really thanks.
    2nd: It's not a good practice use String to call class, if u dont want to use conditionals u can use the hierarchy. Use the abstract class, and u can send to Factory a class instead a String. The same error occurs later.

  32. Kristian Welsh Avatar

    is `if( goldMedal == null )` not a conditional?

  33. Derek Banas Avatar

    Thank you ๐Ÿ™‚ yes, I agree that when people first learn about design patterns they tend to over use them. This is definitely true with the singleton pattern

  34. Raaaaaaaaaafls Avatar

    Thanks for answering!, loving all your videos so far, they are really interesting and it is quite awesome that you are spreading all this knolwege for free. This example was pretty good, and the challenge was not easy, it's just that i am not a big fan of singletons, i think people tend to abuse them very often. Anyway, keep on with the videos!

  35. Derek Banas Avatar

    Yes I agree, but I'm trying to teach design patterns. I'm sorry if the examples aren't perfect. Very often I make these up as I go and I do my best to make interesting videos on extremely niche topics. I hope that helps explain ๐Ÿ™‚

  36. Raaaaaaaaaafls Avatar

    This could be so much simple if you didn't use singleton for winner classes…instead, you could declare a HashMap (Key = WinnerType, Value = Athlete) in the factory and store by default three instances for each type if winner having as key a WinnerType(gold, silver…), which could be an๏ปฟ enum for example. Also if asked for a winner wich is neither silver, gold, or bronze, just return new Athlete or DefaultAthlete…
    Thanks for reading, just my own suggestion.

  37. Derek Banas Avatar

    I figured it was something silly. I've done that hundreds of thousands of time ๐Ÿ™‚

  38. Karim Ihab Avatar

    NVM, I've got it
    I hade to write the package name before the class name in "Class.ForName",
    I can't believe I've been looking for three hours.

  39. Karim Ihab Avatar

    Hey Derek any suggestion on the ClassNotFoundException !!!!
    the import didn't work out

  40. Karim Ihab Avatar

    Ah my bad you've got
    "throw new IllegalArgumentException", sorry

  41. Karim Ihab Avatar

    Plus "getCustomer" method needs "return null" or something
    and you didn't right that in the code sample in the link.

  42. Karim Ihab Avatar

    Nop, But it didn't work any way !!!? ๐Ÿ˜€
    I've searching and I couldn't find something.. the results says that the problem may be in my classPath !!!
    how come

  43. Derek Banas Avatar

    Did you import java.lang.reflect.Method ?

    I fixed the link. Thank you for telling me ๐Ÿ™‚

  44. Karim Ihab Avatar

    Also the code link is down

Leave a Reply

Your email address will not be published. Required fields are marked *