This document discusses refactoring code to improve its design without changing external behavior. It notes that refactoring involves making small, incremental changes rather than large "big bang" refactorings. Code smells that may indicate a need for refactoring include duplication, long methods, complex conditional logic, speculative code, and overuse of comments. Techniques discussed include extracting methods, removing duplication, using meaningful names, removing temporary variables, and applying polymorphism. The document emphasizes that refactoring is an investment that makes future changes easier and helps avoid bugs, and encourages learning from other programming communities.
Refactoring of code for more readable, scalable modules based on The book titled "Refactoring - Improving the Design of Existing Code" written by Martin Fowler
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
Many teams adopt TDD attracted by the promise of a more productive workflow, fewer regressions and higher code quality. Sometimes this goes wrong and these benefits do not materialise, despite a healthy-seeming test suite. In this talk we will look at what the common pitfalls of testing are, why teams fall into these traps, and they can dig themselves out.
Finding the Right Testing Tool for the JobCiaranMcNulty
Over the last decade the idea that we should test our applications has slowly made its way from a niche idea to the mainstream of PHP development. With many tools and approaches to testing now available it can be difficult to choose which ones to use.
In this talk we will explore the current landscape of PHP testing practices, look at the different tools and approaches available, and find out how we can decide which are best for our project, team, and context.
JavaScript is scripting/programming language. File Extension of JavaScript is ".js”. This extension can be catched by a number of applications including Windows Script Host, Dreamweaver MX, Notepad, Netscape Navigator, PavScrip, UltraEdit.
Refactoring of code for more readable, scalable modules based on The book titled "Refactoring - Improving the Design of Existing Code" written by Martin Fowler
Why Your Test Suite Sucks - PHPCon PL 2015CiaranMcNulty
Many teams adopt TDD attracted by the promise of a more productive workflow, fewer regressions and higher code quality. Sometimes this goes wrong and these benefits do not materialise, despite a healthy-seeming test suite. In this talk we will look at what the common pitfalls of testing are, why teams fall into these traps, and they can dig themselves out.
Finding the Right Testing Tool for the JobCiaranMcNulty
Over the last decade the idea that we should test our applications has slowly made its way from a niche idea to the mainstream of PHP development. With many tools and approaches to testing now available it can be difficult to choose which ones to use.
In this talk we will explore the current landscape of PHP testing practices, look at the different tools and approaches available, and find out how we can decide which are best for our project, team, and context.
JavaScript is scripting/programming language. File Extension of JavaScript is ".js”. This extension can be catched by a number of applications including Windows Script Host, Dreamweaver MX, Notepad, Netscape Navigator, PavScrip, UltraEdit.
It contains basic fundamental of class, object, method overloading, constructor, destructor, visibility, acess specifier, Methods, overloading, clonning of objects etc. are covered here.
Kindly look at it and give your comments to improve it as good as possible ways.
Practical tips for dealing with projects involving legacy code. Covers investigating past projects, static analysis of existing code, and methods for changing legacy code.
Presented at PHP Benelux '10
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Good and Bad Code
The Broken Window Theory
The Grand Redesign in the Sky
The Sushi Chef Rule
The Hotel Room Rule
The Boy Scout Rule
OOP Patterns and Principles
SOLID Principles
How to measure clean code?
Tools
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
A JavaScript function is a block of code designed to perform a particular task.
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
It contains basic fundamental of class, object, method overloading, constructor, destructor, visibility, acess specifier, Methods, overloading, clonning of objects etc. are covered here.
Kindly look at it and give your comments to improve it as good as possible ways.
Practical tips for dealing with projects involving legacy code. Covers investigating past projects, static analysis of existing code, and methods for changing legacy code.
Presented at PHP Benelux '10
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
We rarely dive into current programming languages, touting the next new framework or the new features that will be out next year. This is about JavaScript the language as it exists today, what I picked up in going from C# to JS, and what C# picked up from JS along the way as well. It is based on Douglas Crockford's seminal book "JavaScript: The Good Parts".
Good and Bad Code
The Broken Window Theory
The Grand Redesign in the Sky
The Sushi Chef Rule
The Hotel Room Rule
The Boy Scout Rule
OOP Patterns and Principles
SOLID Principles
How to measure clean code?
Tools
Spring boot is a suite, pre-configured, pre-sugared set of frameworks/technologies to reduce boilerplate configuration providing you the shortest way to have a Spring web application up and running with smallest line of code/configuration out-of-the-box.
A JavaScript function is a block of code designed to perform a particular task.
Why Functions?
You can reuse code: Define the code once, and use it many times. You can use the same code many times with different arguments, to produce different results.
LINSEN an efficient approach to split identifiers and expand abbreviationsValerio Maggio
"Linsen an efficient approach to split identifiers and expand abbreviations"
Slides presented at the International Conference of Software Maintenance (ICSM) 2012, Riva del Garda (TN), Italy
Improving Software Maintenance using Unsupervised Machine Learning techniquesValerio Maggio
"Improving Software Maintenance using Unsupervised Machine Learning techniques": Ph.D. defence presentation.
Unsupervised Machine Learning techniques have been used to face different software maintenance issues such as Software Modularisation and Clone detection.
Adam Culp will talk about refactoring code. (The practice of altering code to make it cleaner, simpler, and sometimes faster, while not sacrificing functionality.) We all hate to do it, but it is a necessary evil. So lets talk about how to do it better. Adam will discuss: When to refactor. How to refactor. Why to refactor. How a refactor can help us write better code in the future. A common methodology and steps to follow while refactoring. Resources to help us all on our refactor journey.
Ten useful JavaScript tips & best practicesAnkit Rastogi
In this presentation there are ten useful JavaScript techniques which can be included in your application easily with less friction along with some AngularJs tips and best practices as a bonus. These tips and best practices are accompanied by examples & will cover script loading, design pattern, performance optimization and other areas.
Since best practices are very subjective topics, proper benchmarking needs to be done.
Improving android experience for both users and developersPavel Lahoda
Android UI and User Experience has changed dramatically in the recent version(s) and while users generally enjoy the new features, there are still several areas that are left to application-level-DIY-patterns. For developers, this is double challenge, they want to provide users with the bleeding edge UI patterns and at the same time, they have to deal with evolving API, that sometimes changes dramatically.
Presentation covers the gotchas developer might face dealing with ever-moving Android API, and how to utilize Java language and the tools it have to make the experience for developer more pleasant. Typical trends in the API will get analyzed and divided into several areas or "patterns", discussing typical scenarios how these components are designed and implemented.
This talk will propose several such UI patterns, that will compete to become "de facto" standards and details on the implementation, including possible impact on existing API as we have both end users and developers in mind.
The list of patterns/areas discussed in the talk include following :
ActionBar
ListView
TimePicker
KineticGestureComponent
In depth overview of the Flex data binding code generation. Provides info on accomplish data binding through actionscript as well as limitations of the process.
/*!
* Modernizr v2.0.6
* http://www.modernizr.com
*
* Copyright (c) 2009-2011 Faruk Ates, Paul Irish, Alex Sexton
* Dual-licensed under the BSD or MIT licenses: www.modernizr.com/license/
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in
* the current UA and makes the results available to you in two ways:
* as properties on a global Modernizr object, and as classes on the
* element. This information allows you to progressively enhance
* your pages with a granular level of control over the experience.
*
* Modernizr has an optional (not included) conditional resource loader
* called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
* To get a build that includes Modernizr.load(), as well as choosing
* which tests to include, go to www.modernizr.com/download/
*
* Authors Faruk Ates, Paul Irish, Alex Sexton,
* Contributors Ryan Seddon, Ben Alman
*/
window.Modernizr = (function( window, document, undefined ) {
var version = '2.0.6',
Modernizr = {},
// option for enabling the HTML classes to be added
enableClasses = true,
docElement = document.documentElement,
docHead = document.head || document.getElementsByTagName('head')[0],
/**
* Create our "modernizr" element that we do most feature tests on.
*/
mod = 'modernizr',
modElem = document.createElement(mod),
mStyle = modElem.style,
/**
* Create the input element for various Web Forms feature tests.
*/
inputElem = document.createElement('input'),
smile = ':)',
toString = Object.prototype.toString,
// List of property values to set for css tests. See ticket #21
prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),
// Following spec is to expose vendor-specific style properties as:
// elem.style.WebkitBorderRadius
// and the following would be incorrect:
// elem.style.webkitBorderRadius
// Webkit ghosts their properties in lowercase but Opera & Moz do not.
// Microsoft foregoes prefixes entirely elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
// when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
// with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
// http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
style = ['', ''].join('');
div.id = mod;
div.innerHTML += style;
docElement.appendChild(div);
ret = callback(div, rule);
div.parentNode.removeChild(div);
return !!ret;
},
// adapted from matchMedia polyfill
// by Scott Jehl and Paul Irish
// gist.github.com/786768
testMediaQuery = function( mq ) {
if ( window.matchMedia ) {
return matchMedia(mq).matches;
}
var bool;
injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', funct ...
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
Using Backbone.js to move state to the client-side and the benefits of using a JavaScript MVC framework.
Delivered at SuperMondays, Newcastle upon Tyne, on 26th September 2011.
Object-Oriented JavaScript presentation given at the 2010 ESRI Developer Summit. Code and slides are also available at http://github.com/kvangork/OOJS-Presentation
Find me on twitter @kvangork
or my blog http://prng.vangorkom.org
Object-Oriented JavaScript presentation given at ESRI's 2010 Developer Summit. Slides and code available at http://github.com/kvangork/OOJS-Presentation
Find me on twitter @kvangork
or at my blog: http://prng.vangorkom.org
Lessons from developing Jelly Splash, hit puzzle game from Wooga: multiplatform mobile strategy, using analytics to inform decisions, doing QA without testers.
A talk originally given at CodeFest 2014 in Novosibirsk.
Essential part of any craft is mastering the tools. Programming is no different.
The talk demonstrates newest and lesser known features of development tools built into Firefox and Chrome.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Elevating Tactical DDD Patterns Through Object CalisthenicsDorra BARTAGUIZ
After immersing yourself in the blue book and its red counterpart, attending DDD-focused conferences, and applying tactical patterns, you're left with a crucial question: How do I ensure my design is effective? Tactical patterns within Domain-Driven Design (DDD) serve as guiding principles for creating clear and manageable domain models. However, achieving success with these patterns requires additional guidance. Interestingly, we've observed that a set of constraints initially designed for training purposes remarkably aligns with effective pattern implementation, offering a more ‘mechanical’ approach. Let's explore together how Object Calisthenics can elevate the design of your tactical DDD patterns, offering concrete help for those venturing into DDD for the first time!
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Generating a custom Ruby SDK for your web service or Rails API using Smithyg2nightmarescribd
Have you ever wanted a Ruby client API to communicate with your web service? Smithy is a protocol-agnostic language for defining services and SDKs. Smithy Ruby is an implementation of Smithy that generates a Ruby SDK using a Smithy model. In this talk, we will explore Smithy and Smithy Ruby to learn how to generate custom feature-rich SDKs that can communicate with any web service, such as a Rails JSON API.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
11. Martin Fowler
“Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.”
From the book “Refactoring”:
http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672
12. ;
It’s much more important to write code that will be easy to understand by other people
than just understood by a browser.
14. clarity
enables
performance
Some of you have heard that “Premature optimization is the root of all evil”.
It's easier to optimize clean code than to clean up "optimized" code.
16. Code is like cheese.
Some people find smelly what other find deliciously wonderful.
17. duplication
It makes change harder.
The rule of 3: the third time you copy something, it’s time to refactor.
18. long methods
More than 10 lines is long. This rule is arbitrary to force you to stop and think when you
exceed this size.
A method should do one thing!
19. switch/if
statements
When they’re long and complex.
20. speculative
code
Remove any code that “may be useful later”. You can always recover it from version control.
Very often such code is NEVER nedeed and just confuses people who encounter it.
23. jslint
jshint
Static analysis tools that detect mistakes and enforce clear style.
Using lint was the single most important boost to my productivity in writing JS
24. John Carmack
“Anything that isn’t crystal clear to a static analysis tool
probably isn’t clear to your fellow programmers”.
From John Carmack’s great article on static analysis tools:
http://altdevblogaday.com/2011/12/24/static-code-analysis/
29. What you learned about webstandards and clean front-end code is still valid. These are the
basics:
* Separation of concerns.
* Use CSS for styling.
* Don’t inline JavaScript.
* Assemble HTML in templates.
31. };
if(this.target.entity.contractState === "started") {
var progress = document.querySelector('.progress div'),
timer = document.getElementById('timeLeft');
progress.style.width = Math.floor((((new Date()).getTime() - millisecondsStart) /
millisecondsTotal) * 100) + "%";
counter = setInterval(function () {
var now = new Date().getTime(), timeFromStart = now - millisecondsStart;
if((timeFromStart / millisecondsTotal) >= 1) {
clearInterval(counter);
}
timer.innerHTML = utils.formatTime(millisecondsTotal - timeFromStart);
progress.style.width = Math.floor((timeFromStart / millisecondsTotal) * 100) + "%";
}, 1000);
}
utils.publish('view:entity/focused', {
"entity": entity,
"entityView": entity.entityView,
"infoMode": this
});
//TODO move to pubsub
// show boost info in influence area of decoration
if (this.target instanceof wooga.castle.DecorationView) {
this.target.entity.game.publish("decoration/showBoost", {
entityView: this.target,
x: this.target.entity.x,
y: this.target.entity.y
});
}
// show boost of houses or farmfields in info mode
if (this.target instanceof wooga.castle.FarmFieldView ||
this.target instanceof wooga.castle.HouseView) {
if (this.target.entity.boost) {
this.target.entity.entityView.showBoostInfo = true;
}
}
this.show();
};
Real code, one method, ~150 lines.
32. Extract method
if(this.target.entity.contractState === "started") {
var progress = document.querySelector('.progress div'),
timer = document.getElementById('timeLeft');
progress.style.width = Math.floor((((new Date()).getTime() -
millisecondsStart) / millisecondsTotal) * 100) + "%";
counter = setInterval(function () {
var now = new Date().getTime(), timeFromStart = now - millisecondsStart;
if((timeFromStart / millisecondsTotal) >= 1) {
clearInterval(counter);
}
timer.innerHTML = utils.formatTime(millisecondsTotal - timeFromStart);
progress.style.width = Math.floor((timeFromStart / millisecondsTotal) *
100) + "%";
}, 1000);
}
this.showProgressBar(startTime,requiredTime);
Extract chunk that does one thing into a separate method.
33. Replace comments
// show boost info in influence area of decoration
if (this.target instanceof wooga.castle.DecorationView) {
this.target.entity.game.publish("decoration/
showBoost", {
entityView: this.target,
x: this.target.entity.x,
y: this.target.entity.y
});
}
this.showBoosts(entity);
Well-named method makes comment unnecessary.
35. Replace temp with a query
var text = entity.getInfoModeString();
infoPanel.innerHTML = '<div>' + text + '</div>';
infoPanel.innerHTML =
'<div>' + entity.getInfoModeString() + '</div>';
If temporary variable is used only once, it doesn’t make sense to introduce it.
Sometimes even two calls don’t justify a temporary variable, unless they’re expensive and you
want to cache the results.
37. Use meaningful names
var p = this.current.params;
var r = this.current.results;
if (r.restProduct) {
p.query = r.restProduct;
}
var params = this.current.params;
var results = this.current.results;
if (results.restProduct) {
params.query = results.restProduct;
}
There are 2 hard things in CS: “cache invalidation and naming things”.
Leave compression to minifiers!
38. Use polymorphism
if (entity.is('house')) {
if(entity.contractState === "started") {
var gold = entity.getContractValue();
bulk = '<p>Gives you '+ gold + ' coins</p>';
} else {
bulk = bulk || '<p>Please connect to road</p>';
}
} else if (entity.is('farm')) {
var food = entity.getContractValue();
bulk = '<p>Gives you ' + food + ' food</p>';
} else if (entity.is('ship')) {
bulk = '<p>Repair complete in ' + time + '</span></p>';
}
var bulk = entity.getInfoModeString();
Each entity class implements its own version of the method.
39. this.target = config.target;
var entity = this.target.entity,
entityName = entity.getProperName(),
bulk = entity.getInfoModeString(),
html = '<h1>' + entityName + '</h1><div class=specification>{bulk}</div>',
millisecondsStart, millisecondsTotal, millisecondsEnd, millisecondsLeft;
if(entity.is('decoration')) {
this.target.makeDynamic();
}
this.infoPanel.innerHTML = "";
if(entity.contract) {
millisecondsStart = entity.contractStartTime;
millisecondsTotal = entity.contract.requiredTime;
millisecondsEnd = (new Date()).getTime() - this.target.entity.contractStartTime;
millisecondsLeft = millisecondsTotal-millisecondsEnd;
if (entity.is('any house')) {
if(this.target.entity.contractState === "started") {
var gold = this.target.entity.getContractValue();
bulk = '<div class="progress"><div style="width: 0%;"></div></div><p>Gives you '+
gold +
' coins in <span id="timeLeft">'+utils.formatTime(millisecondsLeft)+'</span></
p>';
} else {
bulk = bulk || '<p>Please connect to road</p>';
}
} else if (entity.is('farm')) {
var food = this.target.entity.getContractValue();
bulk = '<div class="progress"><div style="width: 0%;"></div></div><p>Gives you ' +
food + InfoMode.prototype.activate = function (config) {
' food in <span id="timeLeft">'+utils.formatTime(millisecondsLeft)+'</span></p>'; this.target = config.target;
} else if (entity.is('ship')) {
if(this.target.entity.contractState === "started") {
var entity = this.target.entity;
bulk = '<div class="progress"><div style="width: 0%;"></div></div><p>Repair
complete in <span id="timeLeft">' + if (entity.is('castle') && wooga.castle.playerData.upgradingCastle) {
utils.formatTime(millisecondsLeft) + '</span></p>';
}
wooga.castle.CastleCompleteScreen.instance().show();
} this.deactivate();
this.manager.setMode(wooga.castle.GameModesManager.Mode.BASIC);
}
else {
return;
if(entity.is('castle')) { }
if(wooga.castle.playerData.upgradingCastle) {
wooga.castle.CastleCompleteScreen.instance().show();
if (entity.is('decoration')) {
this.deactivate(); this.target.makeDynamic();
this.manager.setMode(wooga.castle.GameModesManager.Mode.BASIC); }
return;
}
this.infoPanel.innerHTML = '<h1>' + entity.getProperName() + '</h1><div
bulk = '<p><span class="population">Supported Population: ' + class=specification>' + entity.getInfoModeString() + '</div>';
entity.definition.population
+ '</span></p>';
} else if(entity.is('decoration')) { // RADAR: [szafranek] Why is this HERE? Moving it to worldView and listening to
"entity/focused" looks better to me.
bulk = '<p>Nearby buildings get a ';
var concatBoosts = false;
this.manager.view.isFocusedEntityView = function (entityView) {
if (entity.definition.goldBoost) { return entityView === config.target;
bulk += 'gold boost of ' + entity.definition.goldBoost + '%'; };
concatBoosts = true;
}
if (entity.definition.foodBoost) { if (entity.contractState === wooga.castle.House.ContractState.STARTED) {
if(concatBoosts) { this.showProgressBar(entity.contractStartTime,
bulk += '</p><p>and a ';
}
entity.contract.requiredTime);
bulk += 'food boost of ' + entity.definition.foodBoost + '%.'; } else if (entity.contractState ===
} wooga.castle.House.ContractState.CONSTRUCTION) {
}
this.showProgressBar(entity.constructionStartTime,
} entity.contract.constructionTime);
}
this.infoPanel.innerHTML = html.replace('{bulk}', bulk);
this.manager.view.isFocusedEntityView = function (entityView) { utils.publish('view:entity/focused', {
return entityView === config.target; "entity": entity,
};
"entityView": entity.entityView,
if(this.target.entity.contractState === "started") { "infoMode": this
var progress = document.querySelector('.progress div'), });
timer = document.getElementById('timeLeft');
progress.style.width = Math.floor((((new Date()).getTime() - millisecondsStart) /
millisecondsTotal) * 100) + "%"; this.showBoosts(entity);
counter = setInterval(function () {
var now = new Date().getTime(), timeFromStart = now - millisecondsStart;
this.show();
if((timeFromStart / millisecondsTotal) >= 1) {
clearInterval(counter); };
}
timer.innerHTML = utils.formatTime(millisecondsTotal - timeFromStart);
progress.style.width = Math.floor((timeFromStart / millisecondsTotal) * 100) + "%";
}, 1000);
}
utils.publish('view:entity/focused', {
"entity": entity,
"entityView": entity.entityView,
"infoMode": this
});
//TODO move to pubsub
// show boost info in influence area of decoration
if (this.target instanceof wooga.castle.DecorationView) {
this.target.entity.game.publish("decoration/showBoost", {
entityView: this.target,
x: this.target.entity.x,
y: this.target.entity.y
});
}
// show boost of houses or farmfields in info mode
if (this.target instanceof wooga.castle.FarmFieldView ||
this.target instanceof wooga.castle.HouseView) {
if (this.target.entity.boost) {
this.target.entity.entityView.showBoostInfo = true;
}
}
this.show();
Original method after refactoring.
};
40. Know where to stop.
Ask yourself: is the further investment wortwhile?
44. Robert C. Martin
“Learning to write clean code is hard work.
It requires more than just the knowledge of principles and patterns.
You must sweat over it. You must practice it yourself, and watch yourself fail.
You must watch others practice it and fail.”
From the book “Clean Code”:
http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882