By: Andrei Uvarov
Java developer
© 2016 Return On Intelligence, Inc. All Rights Reserved
Agenda
Introduction
• Definitions
• Reasons to learn
• Root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Questions: end of sections only
Our workflow
? ? ? ? ?
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Discussions: end of training
Our workflow
?
????
?
?
?
?
? ?
?
?
? ? ? ? ?
© 2016 Return On Intelligence, Inc. All Rights Reserved
Anti-pattern is…
• … a common response to a recurring problem that is usually
ineffective and risks being highly counterproductive.
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Process, solution, actions — obvious, but ineffective
• Alternative solution — working and effective
Anti-pattern includes
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Know your enemy
Goals
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use common terms
– as with patterns
Goals
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Recognize problem early
Goals
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Don’t “walk on known rakes”
Goals
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Haste
Root causes
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Ignorance
Root causes
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Laziness
Root causes
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Arrogance
Root causes
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Summary:
“I don’t have time and I don’t feel like learning all that crap,
I’ll do without!”
Root causes
© 2016 Return On Intelligence, Inc. All Rights Reserved
Agenda
Introduction
• Definitions
• Reasons to learn
• Root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
© 2016 Return On Intelligence, Inc. All Rights Reserved
• The way we code
Methodological anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• The name says it all
– just copy your code fragments
Copy & paste
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Refactoring
– Extract method
– Use IDE tools
Copy & paste — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• If all you have is a hammer, everything looks like a nail
– “Law of the instrument”
Golden hammer
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Look at the problem from another point of view
• Look at another technology
• How many patterns do you remember?
Golden hammer — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Learn more than one tool!
Golden hammer — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Battle for the performance from start
– Repeat for every line you add
– Sacrifice the design if needed
– No need to measure with performance tests!
Premature optimization
© 2016 Return On Intelligence, Inc. All Rights Reserved
• A simple design is easier to optimize
• Measure your performance
• Optimize worst points first
• Mind the 80-20 rule
Premature optimization — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Forget about that performance!
– Design is über alles
– Don’t bother caching
– Copy heavyweight containers
– …? (Add your option)
Premature pessimization
© 2016 Return On Intelligence, Inc. All Rights Reserved
Keep the balance!
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Create your own solution for everything
– and be original…
Reinventing the square wheel
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Be aware of existing solutions, libraries etc.
• Don’t be afraid of them
• But be sure you understand them
Reinventing the square wheel — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Copy & paste
• Golden hammer
• Premature optimization
• Premature pessimization
• Reinventing the square wheel
Methodological anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Our everyday “friends”
Coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Tactical” level
– but can affect project in general
Coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Ongoing improvements
– “Keep your planet clean”
• “Clean code” approach
Coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use unexplained numbers in code
• … or even unexplained strings
• … or explained only in javadocs
Magic numbers
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Solution: Replace with constants
– Easier to read
– Easier to change
Magic numbers — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Add MORE complexity to the solution
– essential complexity: we have a hard problem
– accidental complexity: we have made a problem hard
Accidental complexity
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Solution:
– Avoid “tricky code”
– Check yourself
– Keep cleaning your code
Accidental complexity — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use patterns, technologies, frameworks
without understanding why
• “Full-stackoverflow developer”
Cargo cult programming
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Understand what you are doing
• Learn!
Cargo cult programming — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Guess the problem source
• Don’t use logs, stack traces, local bug reproducing
• Fix the symptoms only
Shot in the dark
© 2016 Return On Intelligence, Inc. All Rights Reserved
Shot in the dark
© 2016 Return On Intelligence, Inc. All Rights Reserved
Shot in the dark
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Tactical: understand the problem before fixing
• Really fix it – not only cure the symptoms
Shot in the dark – solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Strategical: provide yourself with diagnostic tools
– Use logging
– Keep stacktrace
– Document steps
Shot in the dark – solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Just fix and commit: we have QA anyway, no need for self-testing
• Just use this class: there are hardly any restrictions
Blind faith
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Aviation rule: Don’t assume — check!
Blind faith — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Don’t remove any code!
You may need it… sometimes… probably…
Boat anchor
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Is this code working or obsolete?”
Boat anchor — consequences
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “That ancient mess?! We’ll better write a new one!”
Boat anchor — consequences
© 2016 Return On Intelligence, Inc. All Rights Reserved
VCS.
Boat anchor — solution
Just use it.
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Don’t even touch that code!
– It will take time…
– It can affect… something, we don’t even know what!
Lava flow
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Things will get only worse by themselves
Lava flow — consequences
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Write tests before refactoring
– And you will be more confident while cleaning
Lava flow — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Remember?
Keep. Your. Planet. Clean.
Lava flow — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Don’t tell user what’s happening
Error hiding
This should be enough.
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Cause: desire to hide complexity
• Solution:
– simplified message for user
– detailed message in log
– show errors depending on environments
Error hiding — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Just keep adding lines to the method
– Using labels made it even more spicy in olden days
– But you still can do it with IF’s just like that
Spaghetti code
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Clean code” practices
– E.g.: methods not longer than a screen
• Use metrics to stay warned!
Spaghetti code — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
More food!
Ravioli code Lasagna code
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Keep all configuration at hand: have it all in code!
– Usernames, passwords, hosts, paths…
Hard coding
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Properties files
• User input
• External configuration
Hard coding — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• OK, OK, I got it. No more business logic in code!
– Let’s move everything to… database?
Soft coding
There’s definitely something wrong here…
© 2016 Return On Intelligence, Inc. All Rights Reserved
Smart coding!
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Have a special code for every new special case
– Refactoring is for cowards!
Coding by exception
© 2016 Return On Intelligence, Inc. All Rights Reserved
• It is not about try-catch
• New case can be not-so-new
• Adapt your code
Coding by exception — details
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Accidental complexity
• Cargo cult programming
• Shot in the dark
• Blind faith
• Boat anchor
• Lava flow
• Error hiding
• Spaghetti code
• Hard coding
• Soft coding
• Coding by exception
Coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• How to prevent?
Methodological & coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Inspections
• Code reviews
• Metrics
• Mind your technical debt!
Methodological & coding anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Agenda
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
© 2016 Return On Intelligence, Inc. All Rights Reserved
• The way the system is designed
– on classes level
Object-oriented design anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Is circle an ellipse?
Circle-ellipse problem
© 2016 Return On Intelligence, Inc. All Rights Reserved
• No!
…says Liskov’s substitution principle
• Ellipse.stretchX()
– Can not be replaced with Circle!
Circle-ellipse problem
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Return success/failure value; or raise an exception
– OperationNotSupportedException
• Return the new value (no change for Circle)
• Allow for a weaker contract
– stretchX() also calls stretchY() (Surprise!)
• Use immutable objects
• Question the hierarchy
– Circle.asEllipse()
Circle-ellipse problem — solutions
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Let your modules depend on each other
– Enlarge your coupling!
Circular dependency
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Acyclic Dependencies Principle
– Have a Directed Acyclic Graph of dependencies
Circular dependency — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Dependency Inversion Principle
Circular dependency — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• When your domain objects contain little or no business logic
Anemic domain model
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Any benefits?
• Clear separation between logic and data
• “Pure fabrication” pattern support
– “Service” classes
Anemic domain model
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Liabilities?
− Not really object-oriented way
− Data can be inconsistent (no validation)
− Increased coupling
Anemic domain model
© 2016 Return On Intelligence, Inc. All Rights Reserved
• One class to rule them all
Monster object
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Hard to maintain
• No “Single responsibility”
• Testability problems
Monster object — drawbacks
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Beware of: …Driver, …Manager, …System
• Follow SRP
• Use testability as a problem detector
Monster object — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Extend a utility object to have access to its methods
– Bonus: strange hierarchy
– Bonus: unexpected internals
BaseBean
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use delegation
• “Composition over inheritance” principle
– Interfaces help decoupling
BaseBean — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• A retro-style way of shortening constants
• Pollutes the class namespace
• Not a part of implementing class API
Constant interface
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Do it modern style!
– Create a class with constants
– Use static imports
Constant interface — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• When methods order is important
Sequential coupling
Hmm… or maybe?
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Be suspicious about start…(), init…() methods
• Don’t reveal your class details
• Use “Template method” pattern
Sequential coupling — solution
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Circle-ellipse problem
• Circular dependency
• Anemic domain model
• Monster object
• BaseBean
• Constant interface
• Sequential coupling
Object-oriented design anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
• The way the system is designed
– on architectural level
Software design anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
• More features, less benefits
Software bloat
• Plug-ins (extensions, add-ons)
• Similar anti-patterns?
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Architecture?
No time for this!
Big ball of mud
• Reasons:
– business pressure
– developers rotation
• Symptoms
– bugfixing as a main task
– maintenance nightmare
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Everything can be improved
a bit more
– when should you stop?
Gold plating
• Efforts distribution
• Pareto principle (80/20)
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Software bloat
• Big ball of mud
• Gold plating
• …
Software design anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Everyone knows the project is going to fail
– But the truth is hidden to prevent project cancellation
• Alternatively: unreasonable deadline
– And unnecessary overtime work
Death march
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Rely on heroic efforts (of one or more persons)
– Even base estimates on them
Hero mode
• Solutions:
– Make honest estimates
– Distribute tasks
– Don’t reward heroic behavior
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “No-no, we cannot do anything in this module without John!”
• “I don’t know about it. Ask Mary, she has written all this code.”
• “I like to work alone. It’s just my way of working.”
Lonely rider
• Solutions:
– If you have an irreplaceable person — replace him ASAP
– Knowledge sharing
– Peer reviews
– Mentoring to less experienced
developers
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Pay too much attention to measurement data
– Due to your ignorance or on purpose
Metric abuse
• Solutions:
– Ensure that everyone understands metrics meanings
– Remember: metrics are means, not goals
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Seagull manager
– flies in,
– makes a lot of noise,
– craps on everything
– and flies out again.
Seagull management
• Solutions:
– … show him this definition?
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Death march
• Hero mode
• Lonely rider
• Metrics abuse
• Seagull management
• …
Project management anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Measure thrice and cut once”
– Some people prefer to measure even more times…
Analysis paralysis
• In software development:
long phases of
– project planning
– requirements gathering
– program design
– …
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Two heads are better than one”
– The more heads, the better?
Design by committee
• Many contributors, but no unifying vision
© 2016 Return On Intelligence, Inc. All Rights Reserved
Escalation of commitment
• English proverb: “Throw good money after bad”
• Examples:
– Bidding wars (“Dollar auction”)
– Trying to revive the inevitably dying project
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use a vendor you can’t change without losses
Vendor lock-in
• Examples:
– SIM locking
– Gift certificates
– Sony Memory Stick
– External service or framework
• Solution:
– Isolation layer
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Analysis paralysis
• Design by committee
• Escalation of commitment
• Vendor lock-in
Organizational anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Use link text that does not correspond to the target
“Click here”
For downloading demo version, click here.
For reading the online documentation, click here.
You can download demo version
or read the online documentation,
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Open your menu on hover, not on click
– And hide it once the cursor is out
– That will train visitors’ fine motor skills. And patience.
Hover menus
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Make important icon/link too small
– Yes, fine motor skills again
Tiny targets
► Gadgets
► Buildings
► Food
▼ Transport
► DeLorean
► Hoverboard
Only bullets are clickable
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Is it a switch or an indicator?
Mixing status and action
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Let switch indicate its state:
Mixing status and action
© 2016 Return On Intelligence, Inc. All Rights Reserved
• Show all the power of your software at once!
Bloated interface
© 2016 Return On Intelligence, Inc. All Rights Reserved
• “Click here”
• Hover menus
• Tiny targets
• Mixing status and action
• Bloated interface
UI anti-patterns
© 2016 Return On Intelligence, Inc. All Rights Reserved
Introduction
• definitions
• reasons to learn
• root causes
Methodological APs
Coding APs
OOD APs
Software design APs
Project Management APs
Other AP examples
Agenda
© 2016 Return On Intelligence, Inc. All Rights Reserved
One problem…
Conclusion
© 2016 Return On Intelligence, Inc. All Rights Reserved
Different layers…
Conclusion
© 2016 Return On Intelligence, Inc. All Rights Reserved
Different anti-patterns
Conclusion
© 2016 Return On Intelligence, Inc. All Rights Reserved
Any other examples?
Conclusion
© 2016 Return On Intelligence, Inc. All Rights Reserved
Hope for your feedbacks!
Thank you
© 2016 Return On Intelligence, Inc. All Rights Reserved
Thank you
Andrei I. Uvarov
Java developer
andrew.uvarov@returnonintelligence.com

Anti-patterns

  • 1.
  • 2.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Agenda Introduction • Definitions • Reasons to learn • Root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples
  • 3.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Questions: end of sections only Our workflow ? ? ? ? ?
  • 4.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Discussions: end of training Our workflow ? ???? ? ? ? ? ? ? ? ? ? ? ? ? ?
  • 5.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Anti-pattern is… • … a common response to a recurring problem that is usually ineffective and risks being highly counterproductive.
  • 6.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Process, solution, actions — obvious, but ineffective • Alternative solution — working and effective Anti-pattern includes
  • 7.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Know your enemy Goals
  • 8.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use common terms – as with patterns Goals
  • 9.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Recognize problem early Goals
  • 10.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Don’t “walk on known rakes” Goals
  • 11.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Haste Root causes
  • 12.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Ignorance Root causes
  • 13.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Laziness Root causes
  • 14.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Arrogance Root causes
  • 15.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Summary: “I don’t have time and I don’t feel like learning all that crap, I’ll do without!” Root causes
  • 16.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Agenda Introduction • Definitions • Reasons to learn • Root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples
  • 17.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • The way we code Methodological anti-patterns
  • 18.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • The name says it all – just copy your code fragments Copy & paste
  • 19.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Refactoring – Extract method – Use IDE tools Copy & paste — solution
  • 20.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • If all you have is a hammer, everything looks like a nail – “Law of the instrument” Golden hammer
  • 21.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Look at the problem from another point of view • Look at another technology • How many patterns do you remember? Golden hammer — solutions
  • 22.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Learn more than one tool! Golden hammer — solutions
  • 23.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Battle for the performance from start – Repeat for every line you add – Sacrifice the design if needed – No need to measure with performance tests! Premature optimization
  • 24.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • A simple design is easier to optimize • Measure your performance • Optimize worst points first • Mind the 80-20 rule Premature optimization — solutions
  • 25.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Forget about that performance! – Design is über alles – Don’t bother caching – Copy heavyweight containers – …? (Add your option) Premature pessimization
  • 26.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Keep the balance!
  • 27.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Create your own solution for everything – and be original… Reinventing the square wheel
  • 28.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Be aware of existing solutions, libraries etc. • Don’t be afraid of them • But be sure you understand them Reinventing the square wheel — solution
  • 29.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Copy & paste • Golden hammer • Premature optimization • Premature pessimization • Reinventing the square wheel Methodological anti-patterns
  • 30.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 31.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Our everyday “friends” Coding anti-patterns
  • 32.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Tactical” level – but can affect project in general Coding anti-patterns
  • 33.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Ongoing improvements – “Keep your planet clean” • “Clean code” approach Coding anti-patterns
  • 34.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Coding anti-patterns
  • 35.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use unexplained numbers in code • … or even unexplained strings • … or explained only in javadocs Magic numbers
  • 36.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Solution: Replace with constants – Easier to read – Easier to change Magic numbers — solution
  • 37.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Add MORE complexity to the solution – essential complexity: we have a hard problem – accidental complexity: we have made a problem hard Accidental complexity
  • 38.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Solution: – Avoid “tricky code” – Check yourself – Keep cleaning your code Accidental complexity — solution
  • 39.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use patterns, technologies, frameworks without understanding why • “Full-stackoverflow developer” Cargo cult programming
  • 40.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Understand what you are doing • Learn! Cargo cult programming — solution
  • 41.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Guess the problem source • Don’t use logs, stack traces, local bug reproducing • Fix the symptoms only Shot in the dark
  • 42.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Shot in the dark
  • 43.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Shot in the dark
  • 44.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Tactical: understand the problem before fixing • Really fix it – not only cure the symptoms Shot in the dark – solutions
  • 45.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Strategical: provide yourself with diagnostic tools – Use logging – Keep stacktrace – Document steps Shot in the dark – solutions
  • 46.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Just fix and commit: we have QA anyway, no need for self-testing • Just use this class: there are hardly any restrictions Blind faith
  • 47.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Aviation rule: Don’t assume — check! Blind faith — solutions
  • 48.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Don’t remove any code! You may need it… sometimes… probably… Boat anchor
  • 49.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Is this code working or obsolete?” Boat anchor — consequences
  • 50.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “That ancient mess?! We’ll better write a new one!” Boat anchor — consequences
  • 51.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved VCS. Boat anchor — solution Just use it.
  • 52.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Don’t even touch that code! – It will take time… – It can affect… something, we don’t even know what! Lava flow
  • 53.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Things will get only worse by themselves Lava flow — consequences
  • 54.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Write tests before refactoring – And you will be more confident while cleaning Lava flow — solutions
  • 55.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Remember? Keep. Your. Planet. Clean. Lava flow — solutions
  • 56.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Don’t tell user what’s happening Error hiding This should be enough.
  • 57.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Cause: desire to hide complexity • Solution: – simplified message for user – detailed message in log – show errors depending on environments Error hiding — solutions
  • 58.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Just keep adding lines to the method – Using labels made it even more spicy in olden days – But you still can do it with IF’s just like that Spaghetti code
  • 59.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Clean code” practices – E.g.: methods not longer than a screen • Use metrics to stay warned! Spaghetti code — solutions
  • 60.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved More food! Ravioli code Lasagna code
  • 61.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Keep all configuration at hand: have it all in code! – Usernames, passwords, hosts, paths… Hard coding
  • 62.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Properties files • User input • External configuration Hard coding — solutions
  • 63.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • OK, OK, I got it. No more business logic in code! – Let’s move everything to… database? Soft coding There’s definitely something wrong here…
  • 64.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Smart coding!
  • 65.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Have a special code for every new special case – Refactoring is for cowards! Coding by exception
  • 66.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • It is not about try-catch • New case can be not-so-new • Adapt your code Coding by exception — details
  • 67.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Accidental complexity • Cargo cult programming • Shot in the dark • Blind faith • Boat anchor • Lava flow • Error hiding • Spaghetti code • Hard coding • Soft coding • Coding by exception Coding anti-patterns
  • 68.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • How to prevent? Methodological & coding anti-patterns
  • 69.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Inspections • Code reviews • Metrics • Mind your technical debt! Methodological & coding anti-patterns
  • 70.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Agenda Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples
  • 71.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • The way the system is designed – on classes level Object-oriented design anti-patterns
  • 72.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Is circle an ellipse? Circle-ellipse problem
  • 73.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • No! …says Liskov’s substitution principle • Ellipse.stretchX() – Can not be replaced with Circle! Circle-ellipse problem
  • 74.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Return success/failure value; or raise an exception – OperationNotSupportedException • Return the new value (no change for Circle) • Allow for a weaker contract – stretchX() also calls stretchY() (Surprise!) • Use immutable objects • Question the hierarchy – Circle.asEllipse() Circle-ellipse problem — solutions
  • 75.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Let your modules depend on each other – Enlarge your coupling! Circular dependency
  • 76.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Acyclic Dependencies Principle – Have a Directed Acyclic Graph of dependencies Circular dependency — solution
  • 77.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Dependency Inversion Principle Circular dependency — solution
  • 78.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • When your domain objects contain little or no business logic Anemic domain model
  • 79.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Any benefits? • Clear separation between logic and data • “Pure fabrication” pattern support – “Service” classes Anemic domain model
  • 80.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Liabilities? − Not really object-oriented way − Data can be inconsistent (no validation) − Increased coupling Anemic domain model
  • 81.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • One class to rule them all Monster object
  • 82.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Hard to maintain • No “Single responsibility” • Testability problems Monster object — drawbacks
  • 83.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Beware of: …Driver, …Manager, …System • Follow SRP • Use testability as a problem detector Monster object — solution
  • 84.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Extend a utility object to have access to its methods – Bonus: strange hierarchy – Bonus: unexpected internals BaseBean
  • 85.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use delegation • “Composition over inheritance” principle – Interfaces help decoupling BaseBean — solution
  • 86.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • A retro-style way of shortening constants • Pollutes the class namespace • Not a part of implementing class API Constant interface
  • 87.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Do it modern style! – Create a class with constants – Use static imports Constant interface — solution
  • 88.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • When methods order is important Sequential coupling Hmm… or maybe?
  • 89.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Be suspicious about start…(), init…() methods • Don’t reveal your class details • Use “Template method” pattern Sequential coupling — solution
  • 90.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Circle-ellipse problem • Circular dependency • Anemic domain model • Monster object • BaseBean • Constant interface • Sequential coupling Object-oriented design anti-patterns
  • 91.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 92.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • The way the system is designed – on architectural level Software design anti-patterns
  • 93.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • More features, less benefits Software bloat • Plug-ins (extensions, add-ons) • Similar anti-patterns?
  • 94.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Architecture? No time for this! Big ball of mud • Reasons: – business pressure – developers rotation • Symptoms – bugfixing as a main task – maintenance nightmare
  • 95.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Everything can be improved a bit more – when should you stop? Gold plating • Efforts distribution • Pareto principle (80/20)
  • 96.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Software bloat • Big ball of mud • Gold plating • … Software design anti-patterns
  • 97.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 98.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Everyone knows the project is going to fail – But the truth is hidden to prevent project cancellation • Alternatively: unreasonable deadline – And unnecessary overtime work Death march
  • 99.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Rely on heroic efforts (of one or more persons) – Even base estimates on them Hero mode • Solutions: – Make honest estimates – Distribute tasks – Don’t reward heroic behavior
  • 100.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “No-no, we cannot do anything in this module without John!” • “I don’t know about it. Ask Mary, she has written all this code.” • “I like to work alone. It’s just my way of working.” Lonely rider • Solutions: – If you have an irreplaceable person — replace him ASAP – Knowledge sharing – Peer reviews – Mentoring to less experienced developers
  • 101.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Pay too much attention to measurement data – Due to your ignorance or on purpose Metric abuse • Solutions: – Ensure that everyone understands metrics meanings – Remember: metrics are means, not goals
  • 102.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Seagull manager – flies in, – makes a lot of noise, – craps on everything – and flies out again. Seagull management • Solutions: – … show him this definition?
  • 103.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Death march • Hero mode • Lonely rider • Metrics abuse • Seagull management • … Project management anti-patterns
  • 104.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 105.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Measure thrice and cut once” – Some people prefer to measure even more times… Analysis paralysis • In software development: long phases of – project planning – requirements gathering – program design – …
  • 106.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Two heads are better than one” – The more heads, the better? Design by committee • Many contributors, but no unifying vision
  • 107.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Escalation of commitment • English proverb: “Throw good money after bad” • Examples: – Bidding wars (“Dollar auction”) – Trying to revive the inevitably dying project
  • 108.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use a vendor you can’t change without losses Vendor lock-in • Examples: – SIM locking – Gift certificates – Sony Memory Stick – External service or framework • Solution: – Isolation layer
  • 109.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Analysis paralysis • Design by committee • Escalation of commitment • Vendor lock-in Organizational anti-patterns
  • 110.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 111.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Use link text that does not correspond to the target “Click here” For downloading demo version, click here. For reading the online documentation, click here. You can download demo version or read the online documentation,
  • 112.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Open your menu on hover, not on click – And hide it once the cursor is out – That will train visitors’ fine motor skills. And patience. Hover menus
  • 113.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Make important icon/link too small – Yes, fine motor skills again Tiny targets ► Gadgets ► Buildings ► Food ▼ Transport ► DeLorean ► Hoverboard Only bullets are clickable
  • 114.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Is it a switch or an indicator? Mixing status and action
  • 115.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Let switch indicate its state: Mixing status and action
  • 116.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • Show all the power of your software at once! Bloated interface
  • 117.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved • “Click here” • Hover menus • Tiny targets • Mixing status and action • Bloated interface UI anti-patterns
  • 118.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Introduction • definitions • reasons to learn • root causes Methodological APs Coding APs OOD APs Software design APs Project Management APs Other AP examples Agenda
  • 119.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved One problem… Conclusion
  • 120.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Different layers… Conclusion
  • 121.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Different anti-patterns Conclusion
  • 122.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Any other examples? Conclusion
  • 123.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Hope for your feedbacks! Thank you
  • 124.
    © 2016 ReturnOn Intelligence, Inc. All Rights Reserved Thank you Andrei I. Uvarov Java developer andrew.uvarov@returnonintelligence.com

Editor's Notes

  • #2 Добрый день, меня зовут Андрей Уваров, я Java-разработчик в компании Return on Intelligence. Приветствую вас на вебинаре про антипаттерны в разработке ПО. ==00:05==
  • #3 Пара слов о том, чем мы сегодня займёмся: Начнём мы, естественно, с того, что -- дадим определение, что же это такое, антипаттерны -- выясним, для чего их вообще изучать -- поймём, что приводит к их появлению И потом разберём примеры наиболее часто встречающихся АП Их много, как и паттернов, но можно выделить группы Пойдём, поднимаясь по иерархии, от низких уровней к более высоким От написания кода и до управления проектами Немного обсудим вопросы, которые у нас обязательно возникнут
  • #4 Теперь ещё буквально пара слов о том, как будет построен вебинар Довольно большой объём информации, и чтобы эффективнее использовать наше время, я попрошу записывать вопросы и задавать их в конце раздела
  • #5 В конце вебинара у нас специально запланировано время на обсуждения и любые вопросы по всему материалу Итак, начнём с определения, что такое АП...
  • #6 Антипаттерн – этоооооо... Часто встречающееся плохое решение известных проблем. Например Мы слушаем тренинг Открывается новый слайд Читаем его, пропуская то, что говорит ведущий Не получается толком ни то, ни другое Это и есть антипаттерн Можно и иначе – готовим тренинг пишем на слайде много-много текста потом читаем его или, наоборот, рассчитываем, что написанное уже всяко доведено до слушателей, и говорим совсем другое всё равно неудачно получается Шаблон поведения, вроде бы естественный, напрашивающийся, но на самом деле приводящий к ухудшению ситуации. Мы все знаем про паттерны – это когда у нас есть проблема, и мы делаем что-то, чтобы её решить. А антипаттерн – это когда есть проблема, мы делаем что-то, чтобы её решить, а получается только хуже.
  • #7 Описание АП включает -- некий кажущийся очевидным ответ на проблему, в лучшем случае бесполезный, а то и вредный -- альтернативное решение, работающее и доказавшее свою эффективность -- Говорить про паттерны мы будем в виде вредных советов, паучок на слайде как раз и будет нам их давать.
  • #8 Для чего изучать АП? «Знать врага в лицо» Понимать, что некая ситуация является известной проблемой, сложной или простой, но, как правило, решаемой.
  • #9 «Говорить на одном языке» Использовать одну и ту же терминологию при обсуждениях, поиске информации, обмене опытом. Достаточно сказать «у нас тут образовались магические числа», и собеседник понимает, о чём речь. Аналогично с паттернами.
  • #10 «Вовремя распознать проблему»
  • #11 «Не наступать на известные грабли» В своей работе мы и так достаточно часто встречаемся с «граблями» -- неожиданно возникающими проблемами. Хорошо бы вовремя заметить хотя бы те, по которым уже потоптались до нас.
  • #12 Что вообще приводит к такому шаблонному и ошибочному поведению? Спешка Помните его девиз? «И так сойдёт»
  • #13 Невежество, незнание
  • #14 Лень
  • #15 Самонадеянность
  • #16 «Мне некогда и неохота что-то там учить, справлюсь и так»
  • #17 ==00:10== Со вводной частью мы закончили, давайте перейдём непосредственно к примерам конкретных антипаттернов Начнём с группы, условно названной «методологические»
  • #18 Способы, приёмы нашей работы Именно методология программирования
  • #19 Начну с самого, самого известного и самого всеми любимого антипаттерна – «копипаст» Паучок даёт вредный совет: просто копипастите нужный фрагмент кода туда, где он тоже требуется Известный АП, все мы знаем, что так делать плохо... А, собственно, почему? Если вкратце, в двух словах сформулировать? -- сложность поддержки кода
  • #22 Посмотреть на проблему с другой точки зрения – может, там хоть резьбу увидите? Подумать про другую технологию – пересмотреть свой ящик с инструментами (у вас ведь ящик? Не один только молоток?) Ближайший пример: вы знаете много паттернов? Если их считанные единицы, вы и будете применять в основном их
  • #23 Закону инструмента легче противостоять, если инструментов в арсенале много Чем больше, тем лучше
  • #24 Преждевременная оптимизация Займёмся ею с самого начала Добавили строчку – стали думать, как оптимизировать Если нужно, пожертвуем и дизайном, лишь бы ускорить А раз оптимизируем всё и сразу – то не нужны и пифоманс тесты
  • #25 Проще дизайн – проще оптимизировать Прежде всего измерения, не надо вслепую Если уж оптимизируем, то сначала там, где особо нужно 80/20
  • #26 Иногда можно уйти в другую крайность Дизайн превыше всего Кэширование никому не нужно Копируем объекты не задумываясь ...ещё варианты? Как можно ухудшить пифоманс?
  • #27 Кот как бы говорит нам: соблюдаем баланс Не бросаемся в крайности
  • #28 Изобретение квадратного колеса Два аспекта – и то, что изобретаем уже существующее, и то, что оно получается хуже
  • #29 Знать о существующих решениях Не бояться применять (+ АП «Сделано не здесь») Но понимать, что именно делаешь (+ «Карго-культ»)
  • #30 Закончим на этом с примерами методологических АП Если у вас возникли какие-то вопросы по уже услышанному – самое время их задать, я постараюсь ответить
  • #32 Подстерегают нас, разработчиков, буквально каждый день во время нашей работы
  • #33 Самый «низкий» уровень, но проблемы здесь могут влиять на проект целиком.
  • #34 Как им противостоять? Только постоянным стремлением к улучшению Баобабы проблем лучше выкорчёвывать, пока они маленькие Идеология «Чистого кода» (Роберт Мартин) Предлагает улучшать код понемногу, в процессе работы над задачами проекта. Следите за чистотой кода
  • #35 Разберём некоторые наиболее популярные антипаттерны Не стоит вглядываться в этот код, это пока ещё не антипаттерн, а просто ретро-картинка про кодирование
  • #36  Например: double total = 1.13 * price;
  • #37 Вместо этого: public static final double TAX_RATE = 1.08; (…) double total = TAX_RATE * price; Причём тут надо очень строго оценивать необходимость константы, при малейших сомнениях – лучше определять её. Этой ошибки, кстати, не избежал даже Роберт Мартин в «Чистом коде». «Число 5280 – количество футов в миле – настолько хорошо известно и уникально, что читатель сразу узнает его, даже если оно будет располагаться вне какого-либо контекста.» Забавно, да? Вот в следующий раз, когда вам захочется использовать 86400 прямо в коде, без константы – вспомните этот пример.
  • #38 Видели такой код, правда? Перед вами антипаттерн «Искусственная сложность» В отличие от essential complexity, естественной Причины: Например, изменившиеся бизнес-требования. Было многоступенчатое ветвление, часть веток стала неактуальной. При исправлениях ограничились формальными точечными изменениями. А дерево решений на самом деле уже можно упростить до простого if-else.
  • #39 Решения: * Избегать «хитрого» кода (замысловатого) (помните, может, в программистской юности высшим шиком считалось написать такой код, чтоб был коротким, совершенно непонятным, но делал сразу кучу вещей) Все время спрашивать себя: а то ли я делаю «Чистый код», опять же
  • #40 Программирование методом карго-культа (использование без понимания) Пример: юнит-тест на простейшие сеттеры и геттеры, или на возврат замоканных данных. Технологии «для резюме» -- «Я знаю каратэ, дзюдо, айкидо и ещё много других страшных слов». Популярная разновидность сегодня: Found on Internet («скопипастил со стэковерфлоу») Думаю, большинство из вас знает, что такое карго-культ, но на всякий случай вкратце расскажу...
  • #41 Ну, какое тут может быть решение? Только одно – эволюционировать, для начала из coding-monkey хотя бы в Гомера
  • #42 Выстрел наугад Пытаемся угадать источник проблемы Не используем логи, стектрейсы, не пытаемся воспроизвести у себя Лечим симптомы -> например...
  • #43 Пришли неожиданные данные на вывод – подправить их и показать что-нибудь осмысленное, не разбираясь, откуда неожиданность А неожиданность, например – от заглушенной ошибки в предыдущей обработке (пустой catch)
  • #44 Не надо так!
  • #45 Выстрел наугад Два аспекта решений: -- тактический: понять суть проблемы перед тем, как бросаться решать. Устранять корень ошибки, а не «заметать пыль под коврик».
  • #46 Выстрел наугад Два аспекта решений: -- стратегический: обеспечить себя инструментами диагностики Логирование Анализ стектрейсов Документирование шагов, приведших к ошибке
  • #47 Слепая вера -- в свои силы как программиста: «да должно заработать, там же всё очевидно» -- в силы других программистов: «ну, метод же вроде делает примерно то, что мне нужно, какие там ещё особенности»
  • #48 На веру ничего не принимаем, если нам нужно, чтобы что-то было в определённом состоянии – убеждаемся, что так и есть
  • #50 Непонятно, рабочий это код или уже никем не используемый
  • #51 Даже если до этого куска кода дойдут руки – скорее всего, к тому времени он уже устареет, рассинхронизировавшись с остальным проектом. Чаще всего окажется проще выкинуть его и написать свежий.
  • #53 Поток лавы Масштабная подсистема, модуль, функциональность, на которую постоянно натыкаются, но которую боятся тронуть, потому что непонятно, сколько это займёт и на что повлияет.
  • #54 Само всё обычно только ухудшается
  • #55 Конечно, переделать Пока всё плохо, а не *очень плохо* – избавиться, отрефакторить, оптимизировать. Снизить риски можно тестами
  • #57 Картинка Этого д.б. достаточно
  • #58 * Причина: желание скрыть сложность Крайности – не самый хороший вариант. Не нужно вываливать на юзера дампы памяти (помните в Win95 сообщение об ошибке с кнопкой Details?). * Но хоть указать проблемную область стоит. Например: «не получилось создать файл по такому-то пути», и юзер уже примерно понимает, что можно сделать. А вот стектрейсы ему не нужны, в отличие от вас. Так что логи наше всё. А ещё можно по-разному показывать ошибки на прод и девел энвайрноментах.
  • #60 Чистый код, практики – метод не длиннее страницы, например Метрики для предупреждения
  • #61 Про что это, как считаете?
  • #63 Properites files Спросить у пользователя Внешняя конфигурация – сервер с конфигом
  • #64 Вынесем все правила бизнес-логики в конфигурацию.. В БД, например... Получаем чуть ли не новый язык программирования, чтоб заставить программу работать * что-то тут не так
  • #65 Соблюдаем разумный баланс
  • #66 Программирование через особые ситуации (это не про эксепшны) Новое изменение в требованиях – дописываем код, не глядя на то, что было Рефакторингом не занимаемся Получаем подобные паровозики Ифов Помните, говорили про искусственную сложность?
  • #67 Не про трай-кетч Получив новое условие, проверяем, насколько оно новое – вдруг есть что-то общее с уже существующими Меняем код как целое, адаптируем не только отдельные детали, если нужно
  • #68 Вопросы?
  • #69 Составляем список на доске: Inspections Code reviews Metrics
  • #70 Понятие технического долга – объяснить, если надо
  • #71 ==00:40==
  • #72 То, как система спроектирована На уровне классов – «конкретных деталей»
  • #74 Принцип подстановки (замещения) Кто-нибудь может сформулировать? «если S является подтипом T, тогда объекты типа T в программе могут быть замещены объектами типа S без каких-либо изменений» Барбара Лисков :)
  • #75 Сигнализировать о невозможности операции Возвращать новый тип данных (старый не меняем) Ослабляем контракт, если возможно Используем неизменяемые объекты Пересматриваем иерархию (независимые классы, возможность конвертации)
  • #78 Инверсия зависимости Говорим, что провода из стены должны предоставляться в определённом виде – то есть сервис должен иметь определённый интерфейс Тогда тем, кто его использует, достаточно знать об этом интерфейсе и зависеть уже от него Вроде бы усложнение, но на самом деле жить становится проще
  • #79 Использование объектов, не содержащих бизнес-логики (или мало) * Пример – JavaBeans Это плохо? Можно заметить, что паучка нет. Тонкий приём, имеющий и достоинства, и недостатки, и то и другое надо понимать. Давайте подробнее рассмотрим.
  • #80 * Чёткое разделение данных и логики, возможность отделить данные от их обработки * Класс -«сервис» -- воплощение «бизнес-логики», которому можно передать чистые данные, чтобы он провёл какие-то операции над ними. Объединять эти операции с данными не всегда целесообразно (напр., работа с БД)
  • #81 Недостатки? * Отход от принципов ООП (когда данные знают, как должны быть обработаны) * Может нарушиться непротиворечивость данных (ввели дату смерти, а флаг «умер» не поставили) * Увеличение связности (через объекты данных)
  • #82 Класс всевластья «И один, всесильный...»
  • #83 Сложно поддерживать Отход от принципа «одной ответственности» Проблемы с тестированием
  • #84 Решения – вытекают из недостатков Берегитесь классов с такими именами – они чаще других склонны обращаться к Злу Следуем принципу одной ответственности Проблемы с тестированием как индикатор
  • #85 Пишем утилитный объект, просто предоставляющий функционал Наследуемся от него просто чтобы получить доступ Нелогичная иерархия Неожиданные побочные эффекты и особенности реализации Теперь у машины есть функционал «собирать стряхиваемый пепел» Не надо так!
  • #86 Делегирование Предпочитаем композицию, а не наследование В этом помогают интерфейсы Так-то лучше! Теперь внутри машины есть модуль, работающий с пеплом
  • #87 Загрязняет неймспейс Не является частью API
  • #89 Привязка к последовательности
  • #90 Берегитесь методов с названиями... Не раскрывайте детали реализации – только конструкторы, статические конструкторы, фабрики – единственная точка для всего процесса создания Используйте метод-шаблон – позвольте переопределить некий метод и уже его используйте сами внутри, в жёстко фиксированном сценарии
  • #91 Вопросы?
  • #92 ==01:00==
  • #93 То, как система спроектирована На уровне модулей, подсистем, их взаимодействий Архитектура
  • #94 Раздутое ПО Ваши примеры? Word (+HTML редактор, +веб-инструменты) ICQ (смайлы, реклама, ...) Nero + ACDSee * решения: плагины * similar AP: Spaghetti code Monster object
  • #95 Ком грязи (отсутствие внятной архитектуры) Причины Давление заказчика Текучка кадров Симптомы Багфикс как основная работа Адовая поддержка
  • #96 Бесконечные улучшения, «вылизывания» Это, если кто не разглядел, вертолёт Решения? * Рациональное распределение усилий * Принцип Парето
  • #97 Input kludge (непроверка входных данных) Stovepipe system (дымоходы – каждый дом со своей системой – создание своей авторизации, например) Database-as-IPC (interprocess communication) -- БД для межпроцессной коммуникации
  • #98 ==01:05==
  • #99 Марш смерти Все знают, что проект обречён, но не хотят, чтоб его закрыли Как вариант: нереальный дедлайн, но никто не говорит вслух; ненужные переработки и т.п.
  • #100 Режим супергероя Решения Честные оценки Распределение задач Не поощрять подвиги
  • #101 Одинокий рыцарь *** Отдельный работник становится незаменимым и даже настаивает на том, чтобы работать над областью одному Решения Скорее заменить Распределять знания, не допускать уникальных хранителей Ревью – поощрять общение Обучение внутри команды
  • #102 Придавать слишком большое значение метрикам, метрики как самоцель * По незнанию или намеренно Вопрос: когда злоупотребление метриками может быть намеренным? (с какой целью?) Когда acceptance criteria (95% покрытие кода) Решения Убедиться, что все понимают назначение и смысл Метрики – средство, а не цель
  • #103 Чайка-менеджмент Прилетает Поднимает много шума Гадит на всех Улетает решение Показать ему это определение?
  • #104 … Groupthink Smoke and mirrors
  • #105 ==01:15==
  • #106 Семь раз отмерь, один отрежь Иногда измерения затягиваются... * В разработке ПО: слишком долгие этапы...
  • #107 «Разработка комитетом» Одна голова хорошо, а две лучше А три? А пять? Участников много, но нет общего видения Причины Плохое архитектурное руководство Самолюбие программистов, гордыня (принцип «изобретено не здесь») Недостаток знаний Пренебрежение стандартами (споры вокруг того, что уже можно принять как готовое, то, с чем все согласятся)
  • #108 Продолжение вложений (сверх разумного) Примеры Долларовый аукцион Попытка реанимировать обречённый проект («марш смерти», ага)
  • #109 Привязка к поставщику Примеры Привязка сим-карты Подарочные сертификаты Закрытый протокол ICQ – периодические проблемы у сторонных клиентов при смене протокола Карты памяти для техники Sony Сторонний фреймворк в вашей программе Решение Промежуточный слой доступа
  • #110 … Cash cow Mushroom management (kept in dark, covered with dung, picked up when grown big enough) (Содержать во тьме, подкармливать навозом, срезать, как только подрастут)
  • #111 ==01:25==
  • #113 Открывать меню по наведению, а не нажатию И прятать, когда курсор уходит Тренируем мелкую моторику и терпение
  • #115 Какие пользователи активны?
  • #117 Утилита для группового переименования 
  • #119 ==01:35==
  • #120 Можно заметить, что одна и та же проблема...
  • #121 ...На разных уровнях, слоях...
  • #122 ...проявляется в виде разных АП Искусственная сложность Монстр-объект Раздутое ПО
  • #124 Я очень надеюсь, что вы напишете свои отзывы по результатам вебинара Буду рад, если вы поможете мне улучшить вебинар и напишете, что понравилось и что можно улучшить Я благодарен вам за ваше время, надеюсь, мы провели его с пользой
  • #125 Ещё раз спасибо, теперь я готов ответить на ваши вопросы