46
Welcome to the 37 th Scrum Breakfast

Human programming

Embed Size (px)

Citation preview

PowerPoint Presentation

Welcome to the 37th Scrum Breakfast

1

Human Programming

QuestionWho dont know anything about Human Programming.Who know about Human Programming.Who expertise in Human Programming.

www.axon.vnfb.com/AxonActiveVietNamMy name is TuanLives in Da Nang, Viet NamWorks in Axon Active Viet NamMore than 5 years experience in developmentScrum Master, Team Leader, Software Engineer.

Introduction

www.axon.vnfb.com/AxonActiveVietNamWhat is human programming ?

www.axon.vnfb.com/AxonActiveVietNam

5

What is human programming ?Human programming is cleaning the code or clean code

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name6

How do you know the code is clean ?How many WTF do you say when you read the code ?

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name7

Any other thing apart from WTF ? How many WTH do you say when you read the code ?

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name8

AgendaNamingCommentFunctionUnit testError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name9

AgendaNamingCommentFunctionUnit testError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name10

NamingEverywhereVariable, function, argument, classes, packages.Source file, directory, jar, war, ear,Name, name and nameExample for naming.

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name11

Namingpublic List < int[] > getThem() { List < int[] > list1 = new ArrayList < int[] > (); for (int[] x: theList) if (x[0] == 4) list1.add(x) return list1;}

public List getFlaggedCells() { List flaggedCells = new ArrayList(); for (Cell cell: gameBoard) if (cell.isFlagged()) flaggedCells.add(cell); return flaggedCells;}

www.axon.vnfb.com/AxonActiveVietNamChoosing good names takes time but saves more than it takes. Take care with your names and change them when you find better ones. The name of a variable, function or class should answer the big questions such as why it exists, what it does, how itis used. If a name requires a comment, then the name does not reveal its intent. For example, these names specify what isbeing measured and the unit of that measurement

=======================================

Distinguish names in such a way that the reader knows what the differences offer. For example, the two classesProductInfo and ProductData have different names but the names dont mean anything different, because hereInfo and Data are indistinct noise words.

=======================================Our minds have evolved to deal with spoken language, so take advantage of that when creating names. Also, if you cant pronounce it, you cant discuss it without sounding like an idiot. As an example, note the benefits of using the second version of this variable instead of the first version

===============Tach ra, chinh code, boi mau

12

Namingclass DtaRcrd102 { private Date genymdhms; private Date modymdhms; private final String pszqint = "102"; /* ... */};class Customer { private Date generationTimestamp; private Date modificationTimestamp; private final String recordId = "102"; /* ... */};

www.axon.vnfb.com/AxonActiveVietNamChoosing good names takes time but saves more than it takes. Take care with your names and change them when you find better ones. The name of a variable, function or class should answer the big questions such as why it exists, what it does, how itis used. If a name requires a comment, then the name does not reveal its intent. For example, these names specify what isbeing measured and the unit of that measurement

=======================================

Distinguish names in such a way that the reader knows what the differences offer. For example, the two classesProductInfo and ProductData have different names but the names dont mean anything different, because hereInfo and Data are indistinct noise words.

=======================================Our minds have evolved to deal with spoken language, so take advantage of that when creating names. Also, if you cant pronounce it, you cant discuss it without sounding like an idiot. As an example, note the benefits of using the second version of this variable instead of the first version

===============Tach ra, chinh code, boi mau

13

Namingint d;// elapsed time in daysint ds;int dsm;int faid;

int elapsedTimeInDays;int daysSinceCreation;int daysSinceModification;int fileAgeInDays;More examples:

www.axon.vnfb.com/AxonActiveVietNamEqual or less than 100 linesShould be 20 lines/function, 150 chars/line

14

NamingDont be too clever or humourous with your names.

dont use the name whack() to mean kill()dont use likeholyHandGrenade() to mean deleIetems()

www.axon.vnfb.com/AxonActiveVietNam

15

The hardest thing about choosing good names is that it requires good descriptive skills and a shared cultural background. This is a teaching issue rather than a technical, business, or management issue. As a result, many people in this field do not do it very well. Clean Code: A Handbook of Agile Software Craftsmanship

Naming

www.axon.vnfb.com/AxonActiveVietNam. Please add author of this sentenceGiai thich ko doc lai.16

AgendaNamingCommentFunctionUnit testError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name17

Comment// does the module from the global list depend on the// subsystem we are part of?if (smodule.getDependSubsystems().contains(subSysMod.getSubSystem()))

// this could be rephrased without the comment asArrayList moduleDependees = smodule.getDependSubsystems();String ourSubSystem = subSysMod.getSubSystem();if (moduleDependees.contains(ourSubSystem))

www.axon.vnfb.com/AxonActiveVietNamOne person say 1 sentence about this kind of comment.

18

CommentInputStreamResponse response = new InputStreamResponse();response.setBody(formatter.getResultStream(),formatter.getByteCount());// InputStream resultsStream = formatter.getResultStream();// StreamReader reader = new StreamReader(resultsStream);// response.setContent(reader.read(formatter.getByteCount()));

www.axon.vnfb.com/AxonActiveVietNamPlease remove the commented out code. When you need that you can code again.

19

Comment// Utility method that returns when this.closed is true.// Throws an exception if the timeout is reached.public synchronized void waitForClose (final long timeoutMillis) throws Exception{ if(!closed) { wait(timeoutMillis); If(!closed){ throw new Exception("MockResponseSender could not be closed"); }}}

www.axon.vnfb.com/AxonActiveVietNamRedundant Comments20

CommentPublic API CommentsLegal CommentsExplanation of IntentWarning for consequencereal TODO CommentsRedundant CommentsNoise CommentsPosition MarkersClosing Brace CommentsCommented-Out CodeObsolete CommentsNonpublic JavaDOcs

www.axon.vnfb.com/AxonActiveVietNamPurpose of a comment is to explain code that does not exlain it selfComments do not make up for bad codeDont use a comment when you can use a function or a variable21

AgendaNamingCommentFunctionUnit TestError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name22

Small -> Smaller -> Smaller .Do one thing.Function name with verbs and keywords.No output arguments.No duplicate code.

Function

www.axon.vnfb.com/AxonActiveVietNamEqual or less than 100 linesShould be 20 lines/function, 150 chars/line

23

One level of abstraction (step down rule)

Functionprivate void includeSetupAndTearDownPages() throws Exception { includeSetPages(); includePageContent(); includeTeardownPages(); updatePageContent();}

www.axon.vnfb.com/AxonActiveVietNamNo side effect

Functionpublic boolean checkPassword(String userName, String password) { User user = UserGateWay.findByName(userName); if (user != null){ String codePhrase = user.getPhraseEncodeByPassword(); String phrase = Crytographer.decrypt(codePhrase, password); if (Valid Password.equals(phrase)){ Session.initialize(); return true; } }}

What am I doing here ?I will cause a side effect to this method. I should not be here !!!

www.axon.vnfb.com/AxonActiveVietNam1 present for who can regconize the code.25

void LoadSingleData();void FetchDataFiltered();void GetAllData();void SetDataToView();void SetObjectValue(int value);Functionvoid GetSingleData();void GetDataFiltered();void GetAllData();void LoadDataToView();void SetObjectValue(int value);Coding convention

www.axon.vnfb.com/AxonActiveVietNamYou try to use difference word for GET use GET for these cases.You would like to loading data to a view and set value to object These are 2 cases so you should use 2 difference words.

1 or 2 present here.26

AgendaNamingCommentFunctionUnit TestError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name27

Test code should be maintained to the same standards of quality as production codeKeeping Test CleanUnit Test

www.axon.vnfb.com/AxonActiveVietNam readability.What makes a clean test ?

public void testGetImage(){ Fixture.userDefaultResourceManager(); ResourceManager resourceManager = RWT.getResourceManager(); assertFalse(resourceManager.isRegistered(Fixture.FIRST_IMAGE)); Image firstImage = Graphics.getImage(Fixture.FIRST_IMAGE); String registerPath = getRegisterPath(firstImage); assertTrue(resourceManager.isRegistered(registerPath)); File contextDirectory = new File(Fixture.WEB_CONTEXT_DIRECTORY, ResourceDirectory.DIRECTORY_NAME); assertTrue(new File(contextDirectory, registerPath).exists()); Image secondImage = Graphic.getImage(Fixture.FIRST_IMAGE); assertSame(firstImage, secondImage); Image thirdImage = Graphic.getImage(Fixture.THIRD_IMAGE); String thirdImagePath = getRegisterPath(thirdImage); assertTrue(resourceManager.isRegistered(thirdImagePath)); assertTrue(new File(contextDir, thirdImagePath).exists()); Graphic.getImage(Fixture.FIRST_IMAGE); assertTrue(resourceManager.isRegistered(registerPath));}Three things: readability,Readability,

www.axon.vnfb.com/AxonActiveVietNamWhat do you think about this method ?29

What makes a clean test ?

public void testGetImage(){ Fixture.userDefaultResourceManager(); ResourceManager resourceManager = RWT.getResourceManager(); assertFalse(resourceManager.isRegistered(Fixture.FIRST_IMAGE)); Image firstImage = Graphics.getImage(Fixture.FIRST_IMAGE); String registerPath = getRegisterPath(firstImage); assertTrue(resourceManager.isRegistered(registerPath)); File contextDirectory = new File(Fixture.WEB_CONTEXT_DIRECTORY, ResourceDirectory.DIRECTORY_NAME); assertTrue(new File(contextDirectory, registerPath).exists()); Image secondImage = Graphic.getImage(Fixture.FIRST_IMAGE); assertSame(firstImage, secondImage); Image thirdImage = Graphic.getImage(Fixture.THIRD_IMAGE); String thirdImagePath = getRegisterPath(thirdImage); assertTrue(resourceManager.isRegistered(thirdImagePath)); assertTrue(new File(contextDir, thirdImagePath).exists()); Graphic.getImage(Fixture.FIRST_IMAGE); assertTrue(resourceManager.isRegistered(registerPath));}Too many concepts here, missing clean and recognizable structure

www.axon.vnfb.com/AxonActiveVietNamWho can propose a solution for this method then I will give 1 present.30

What makes a clean test ?

public void testRegisteredFixture(){ Fixture.userDefaultResourceManager(); ResourceManager resourceManager = RWT.getResourceManager(); assertFalse(resourceManager.isRegistered(Fixture.FIRST_IMAGE));}public void testRegisterPath(){ Image firstImage = Graphics.getImage(Fixture.FIRST_IMAGE); String registerPath = getRegisterPath(firstImage); assertTrue(resourceManager.isRegistered(registerPath));}public voif testFileExists(){ File contextDirectory = new File(Fixture.WEB_CONTEXT_DIRECTORY, ResourceDirectory.DIRECTORY_NAME); assertTrue(new File(contextDirectory, registerPath).exists());}public void testSameImage(){ Image secondImage = Graphic.getImage(Fixture.FIRST_IMAGE); assertSame(firstImage, secondImage);}public void testPathThirdImageRegistered(){ Image thirdImage = Graphic.getImage(Fixture.THIRD_IMAGE); String thirdImagePath = getRegisterPath(thirdImage); assertTrue(resourceManager.isRegistered(thirdImagePath));}public void testThirdImageExists(){ Image thirdImage = Graphic.getImage(Fixture.THIRD_IMAGE); String thirdImagePath = getRegisterPath(thirdImage); assertTrue(new File(contextDir, thirdImagePath).exists());}public void testRegisterPath(){ Graphic.getImage(Fixture.FIRST_IMAGE); assertTrue(resourceManager.isRegistered(registerPath));}

www.axon.vnfb.com/AxonActiveVietNamSplitted out in to 7 method and show.31

Arrangeall necessary preconditions and inputs.Acton the object or method under test.Assertthat the expected results have occurred.3A: Arrange, Act, AssertWhats a good structure for a unit test?@Testpublic void testMethodCanDoAnything(){ String normalInputValue = "normal input value"; SuperPowerObject superPowerObject = UltimateClass.ultimate(normalInputValue); assertNotNull(superPowerObject);}

www.axon.vnfb.com/AxonActiveVietNamChange to pro method.32

Fast: Tests should be fast.Independent: Tests should not depend on each other.Repeatable: Tests should be repeatable in any environment.Self-Validating: The tests should have a boolean output. Timely The tests need to be written in a timely fashion.

F.I.R.S.T.What Makes a Good Unit Test?

www.axon.vnfb.com/AxonActiveVietNamAgendaNamingCommentFunctionUnit TestError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name34

Use exceptions rather than return codes

Error handlingpublic void sendShutDown(){ DeviceHandler handler = getHandler(DEV); if (handler != DeviceHandler.INVALID){ retrieveDeviceRecord(handler); if (record.getStatus() != DEVICE_SUSPENDED){ pauseDevice(handler); clearDeviceWorkqueue(handler); closeDevice(handler); } else { logger.log("Device suspended. Unable to shutdown"); } } else { logger.log("Invalid handler for: " + DEV.toString()); }}public void sendShutDown(){ try { tryToShutDown(); } catch (DeviceShutDownError e){ logger.log(e); }}

www.axon.vnfb.com/AxonActiveVietNamCode lai ko dung hinh.35

Use unchecked exceptionsError handlingpublic class ErrorHandling extends RuntimeException {}

public void controller() { try{ service(); } catch (ErrorHandling error) { log.error(error); }}

www.axon.vnfb.com/AxonActiveVietNamDefine the normal flowError handlingpublic void countMeal(){ try { MealExpenese expenese = expenseReportDAO.getMeals(employee.getId()); m_total += expenses.getTotal(); } catch (MealExpensesNotFound exception) { m_total += getMealPerday(); }}

I should not be here again

www.axon.vnfb.com/AxonActiveVietNamWho can discover the problem in this method. 1 present will be given37

Define exception classes in Terms of a Callers NeedsNo logic code in catch exceptionDont Return Null (return an empty collection instead of null)Dont Pass Null into Methods

Error handling

www.axon.vnfb.com/AxonActiveVietNamTake a break

www.axon.vnfb.com/AxonActiveVietNamWorkshopCalculator application with basic functions.Web or standaloneMobile, C#, JavaTurn messy code to clean code.

www.axon.vnfb.com/AxonActiveVietNamOne person say 1 sentence about this kind of comment.

40

WorkshopEach team will have a working example.All of them are messy code.Clean as possible.15 minutes for cleaning.5 minutes for your presentation.

www.axon.vnfb.com/AxonActiveVietNamOne person say 1 sentence about this kind of comment.

41

AgendaNamingCommentFunctionUnit testError handling

www.axon.vnfb.com/AxonActiveVietNam. Please find icon and make animation instead of just a text for attractive slide.. Find some example about meaningful name42

Presentation of Teams

www.axon.vnfb.com/AxonActiveVietNamOne person say 1 sentence about this kind of comment.

43

Scrum Breakfast team

www.axon.vnfb.com/AxonActiveVietNamOne person say 1 sentence about this kind of comment.

44

QuestionWho know more about human programming, clean code

www.axon.vnfb.com/AxonActiveVietNam

Thank you and see you soon 38th Scrum Breakfast.

www.axon.vnfb.com/AxonActiveVietNam

46