Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Codemania - Coupling, Cohesion, Connascence

Codemania - Coupling, Cohesion, Connascence

or One weird trick for better code

josh_robb

April 24, 2015
Tweet

More Decks by josh_robb

Other Decks in Programming

Transcript

  1. Am I a terrible programmer? • Start coding • [typing...]

    • this is easy I’ll just... • ... • 4 hours later • ... • FML - I SUCK
  2. What is Good Design? Simplicity Modularity Loose Coupling Can understand

    one piece without understanding others Design Patterns SOLID
  3. Responsive Design “The more experience a programmer has, the more

    design ideas he knows. The temptation is to put these design ideas in the system now because you just know you’ll need them eventually.” http://pragprog.com/magazines/2009-09/responsive-design
  4. SOLID Principles SOLID is a useful didactic tool but a

    useless decision making tool. Josh Robb (2014)
  5. SOLID Principles TOO ABSTRACT/High Level How do I write: •

    this line of code? • this method • this class • this feature?
  6. How do I anticipate change? You can’t! Trying to is

    a really bad mistake! “Duplication is far cheaper than the wrong abstraction” Sandi Metz
  7. Cohesion “Attempting to divide a cohesive module would only result

    in increased coupling and decreased readability.” Larry Constantine
  8. public interface IHumungousMonolithicDataService { #region Querying Stuff CardPayment GetCardPayment(Party party,

    int transactionId); Result<CardPayment> GetLastCardPayment(Party recipient, Person payer); IEnumerable<Merchant> SearchMerchants(GeoLocation currentCoordinate, Country country, int skip = 0, int take = 20); IEnumerable<Merchant> SearchMerchants(string name, Country userCountry, int skip = 0, int take = 20); IEnumerable<Merchant> GetMerchantRecommendationsForPerson(Person person, int skip = 0, int take = 20); Merchant GetMerchant(int merchantId, bool includeClosed = false); Merchant GetMerchantFromHandle(string handle); Merchant GetMerchantFromIdOrHandle(string idOrHandle); IEnumerable<ReferenceDefinition> GetReferenceDefinitions(Merchant merchant, bool includeRemoved = false); Person GetPerson(int personId); IEnumerable<Merchant> GetPersonsFavouriteMerchants(Person person, int skip = 0, int take = 50); GeoLocation GetPersonsLastKnownLocation(Person person); IEnumerable<Merchant> GetRecipientsForPayer(Person person); void CreateOrUpdatePushpayer(Person person, PushpayerAccountStatus status, int activityScore); #endregion // Huh? void Detach(Entity entity); #region Pushpayer Registration Stuff CreateCustomerResult BeginRegistration(CreateCustomerModel model); void CompleteRegistration(Person person, RegisterSource unknown); RegisterInfoResult RegisterInfo(Guid authToken, RegisterInfoModel info); Result MergeRegistrationWithExistingPerson(Guid registrationToken, Guid authToken); #endregion #region Pushpayer-Admin Own Account Result<MerchantPersonRelationship> AddFavourite(Person person, Merchant merchant); Result<MerchantPersonRelationship> RemoveFavourite(Person person, Merchant merchant); #endregion #region UserLogin / Auth / Security LoginResult Login(string username, string password); SessionToken Authenticate(Guid authToken); LoginResult LoginWeb(string username, string password); Result<SessionToken> AuthenticateWeb(Guid webToken); Result<SessionToken> ValidateSession(Guid sessionToken, SessionType sessionType = SessionType.App); Result<Guid> SendForgotPassword(string email); bool ValidatePasswordResetToken(Guid webToken); bool ResetPassword(Guid webToken, string password); void Logout(Person person, SessionToken sessionToken = null); void FreezeAccount(Person person); #endregion #region Merchant-Admin Own Account Result<MerchantAccountUpdateResultCode> UpdateMerchantInformation(MerchantAccountUpdateModel model, Merchant merchant); Result<MerchantControlTransferResultCode, Merchant> TransferMerchantAdmin(MerchantControlTransferModel model, Merchant merchant); #endregion }
  9. Cohesive. Coupling? public interface IPushpayerPaymentService { PaymentResult CompleteWebPayment(PaymentInfo info, PaymentEvidence

    evidence); GuestPaymentResult CompleteGuestPayment(PaymentInfo info, PaymentEvidence evidence); PaymentResult CompleteMobileApiPayment(PaymentInfo info, PaymentEvidence evidence); }
  10. Coupling? _cowabungaPipelineService = new PaymentCowabungaPipelineService( _gatewayServiceFactory.Object, _paymentDuplicationChecker.Object, _paymentQueryService.Object, _auditLoggerService.Object, _anticipatedPaymentsService.Object,

    _checkGatewayDebitPaymentSubmissionService.Object, _achPaymentViaPipelineService.Object, _paymentMethodEditingService.Object, _eventDispatcher.Object, _webhooksService.Object, _paymentNotificationService.Object, _mailService.Object, _supportMailService.Object, _minionCommander.Object, _authenticatedDeviceService.Object, _cardGatewayConfigurationConsultant.Object, _fieldUIService.Object, _validationService.Object); WAT WAT WAT WAT FML
  11. “Mock setup exposes coupling, remember; not cohesion or other design

    properties.” Gary (again) Read the whole thing! https://www.destroyallsoftware.com/blog/2014/test-isolation-is-about-avoiding- mocks Coupling
  12. “Comparing techniques by means of encapsulation and connascence” Communications of

    the ACM Special issue on analysis and modeling in software development CACM Volume 35 Issue 9, Sept. 1992
  13. Connascence 1. The common birth of two or more at

    the same time. 2. That which is born or produced with another. 3. The act of growing together.
  14. Connascence Connascence is a software quality metric [...] to allow

    reasoning about the complexity caused by coupling
  15. “[...] because it classifies the relative strength of that coupling,

    connascence can be used as a tool to help prioritise what should be refactored first.” Kevin Rutherford http://silkandspinach.net/2015/01/22/connascence-of-value/ Connascence
  16. Connascence Two software components are connascent if a change in

    one would require the other to be modified in order to maintain the overall correctness of the system.
  17. Types of Connascence • Name • Type • Meaning •

    Position • Algorithm • Execution • Timing • Value • Identity
  18. Strength/Degree • Name • Type • Meaning • Position •

    Algorithm • Execution • Timing • Value • Identity Weaker Stronger Degree Few occurrences Many occurrences
  19. Static • Name • Type • Meaning • Position •

    Algorithm Types of Connascence Dynamic • Execution • Timing • Value • Identity
  20. Con of Name class Customer { int Age {get;set} }

    var customer = new Customer(); customer.Age = 27;
  21. Con of Name class Customer { int Age {get;set} }

    var customer = new Customer(); customer.Age = 27;
  22. Con of Name “Doesn’t R# fix this?” (or IDEA or

    Eclipse #lolwat) Well - yes - thats the point - it’s the weakest
  23. Con of Name ALTER TABLE Customer ALTER COLUMN Age INT

    NOT NULL; class Customer { string Age {get;set} } LOCALITY MATTERS
  24. Con of Type Multiple components must agree on type. function

    sayHello(name) { return "hello " + name; } var i = 0; console.log(sayHello(i));
  25. Con of Type Maybe - your compiler (if you have

    one) will catch this - Maybe not.
  26. Con of Position void Save(string name, string address1, string address2,

    string city, string country, string zip); myrerepo.Save(“bob”,“11 St”,“Suburb”,“Kingston”, “Jamaica”,“00234”,); 6 Degrees of Connascence
  27. Con of Position -> Name/Type class User { FirstName, LastName,

    Address } void Save(User); myrerepo.Save(new User { FirstName = “bob”, LastName = “marley”, Address = “jamaica”});
  28. Con of Algorithm var mobileNumber = GetMobileNo(); if(IsValidMobile(mobileNumber)) Particularly tricky

    with Javascript/server side transitions, crypto, interop/integration
  29. Con of Algorithm Routes Map: Url -> Controller/Action /login ->

    AuthController.Login() Views Generate Url. <a href=”/login”>Log In</a>
  30. Con of Algorithm ASP.NET MVC kinda gets this right by

    transforming Con of Algorithm -> Con of Meaning (Action/Controller name strings).
  31. Static vs Dynamic No time for the details • Execution

    (order matters) • Timing (timing matters) • Value (related sets of values) • Identity (GetHashCode/UnitofWork)
  32. Con of Value class Blog { public BlogStatus Status =

    BlogStatus.Draft; } public testBlog() { var blog = new Blog(); Assert.Equal(blog.Status == BlogStatus.Draft); }
  33. Ease of Change Name of a type <-- easy Name

    of a method <-- easy parameters of a method/type <-- harder contract of a method <-- hard.
  34. Thanks • Rob Fonseca-Ensor • Alex Henderson • Jim Weirich

    • Hamilton de Oliveira • Ward Cunningham • Sandi Metz • Gary Bernhardt • Corey Haines