Showing posts with label idea. Show all posts
Showing posts with label idea. Show all posts

Tuesday, March 10, 2015

What is better inversion in method names of inversion operator in usage ?

What is better inversion in method names of in usage ? What criteria we could use measure that ?

For private methods it might be not a problem, but mostly affects API and public methods

@Override
public void visitToken(DetailAST aAst) {
DetailAST conditionExpressionAst = aAst.findFirstToken(TokenTypes.EXPR);
switch (aAst.getType()) {
case TokenTypes.LITERAL_RETURN:
if (isNonEmptyReturn(aAst)) {
DetailAST inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
}
break;
case TokenTypes.LITERAL_WHILE:
case TokenTypes.LITERAL_DO:
case TokenTypes.LITERAL_IF:
DetailAST inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
break;
case TokenTypes.FOR_CONDITION:
if (isNonEmptyForCondition(aAst)) {
inversionAst = getInversion(conditionExpressionAst);
if (isAvoidableInversion(inversionAst)) {
log(inversionAst);
}
}
break;
default:
final String exceptionMsg = "Unexpected Token Type - "
+ TokenTypes.getTokenName(aAst.getType());
throw new IllegalStateException(exceptionMsg);
}
}
code:
/**
* Checks if return statement is not empty
* @param aReturnAst
*/
private static boolean isNonEmptyReturn(DetailAST aReturnAst) {
return aReturnAst.findFirstToken(TokenTypes.EXPR) != null;
}
/**
* Checks if condition in for-loop is not empty
* @param aForConditionAst
*/
private static boolean isNonEmptyForCondition(DetailAST aForConditionAst) {
return aForConditionAst.getFirstChild() != null;
}

Some code could not be written without "NOT"/"NON" , Example:

Static Import Check for Checkstyle

Static import: http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

Command to catch code:
 grep --include=*.java --exclude={*Test.java,Test*.java,*IT.java} -rw -m 1 . -e "import static"

we can not forbid static import usage at all, it is useful, we need to limit it, So we will forbid all static imports that are not applying to following options:

1) allow in target member is used more then X times.
see example in point "3)" and imagine there is a lot of such code blocks, that option could allow static import for "psvBuilder".

2) allow in Class of target member could brake Line-limit more then X times.
 that it is not required as will hide too much code that should be formatted appropriately

3) Allow in complicated statements with a lot of inner methods calls in arguments.

import static com.commons.domain.DsvFileDefinition.psvBuilder;
import static com.commons.domain.FeedDefinition.feedBuilder;
import static com.commons.domain.ZipFileDefinition.zipBuilder;

private static FeedDefinition getFeedDefinition() {
return feedBuilder("Premium", "/datafeeds/", "NAME", "NAME1").addFile(
zipBuilder("premium").addFiles(of(
psvBuilder("address").build(),
psvBuilder("entity").build(),public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

psvBuilder("entity_changes").build(),
psvBuilder("entity_identifiers").build(),
psvBuilder("entity_names").build(),
psvBuilder("entity_profiles").build(),
psvBuilder("entity_relationships").build(),
psvBuilder("entity_structure").build(),
psvBuilder("entity_map").build(),
psvBuilder("listing_map").build())).build()
).build();


4) Ignore list of classes/methods that team presume distinctive and whole team know.
"com.google.common.base.Strings,com.google.common.base.XXXXXXX"

import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.base.Strings.nullToEmpty;

this.schemaName = nullToEmpty(schemaName);
if (isNullOrEmpty(tableName)) {
throw new IllegalArgumentException("tableName could not be empty");
}
this.tableName = tableName;

5)
Invalid usage:
import static com.google.common.collect.Iterables.getFirst;
....

TreeSet<Name> names = Sets.newTreeSet(new ILifeCycleEntityComparator());
if (names.isEmpty()) {
// do smth 
} else {
Name firstName = getFirst(tradenames, null);public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

// do smth else
}

6)
Here looks like static import allow to keep lines short.

import static com.revere.det.core.domain.validation.ValidationUtils.formatPeriod;

details.append("Focused sector: ").append(focusSector.getPath())
.append(", start date of focus: ").append(formatPeriod(focus.getStartDate()))
.append(", end date of focus: ").append(formatPeriod(focus.getEndDate()))
.append(NEW_LINE);

7)
Inappropriate - used only one time in whole file.

import static org.joda.time.LocalDateTime.now;

public class Builder extends DataBuilder {

private static final java.sql.Date THREE_YEARS_AGO = new java.sql.Date(now().minusYears(3).toDate().getTime());

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

https://code.google.com/p/guava-libraries/wiki/FunctionalExplained

Even using static imports, even if the Function and the Predicate declarations are moved to a different file, the first implementation is less concise, less readable, and less efficient.   

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

Here's a shortened version of a class where static import is suitable:

===============================
import static com.some.company.BetPosition.*;

public class NumberMapping {

    private final BetPosition[][] numberToPositions = new BetPosition[][] {
            /* 0 number */{ STRAIGHT_0, BET_0_1, BET_0_2, BET_0_3, BET_0_1_2, BET_0_2_3, BET_0_1_2_3 },                 
            // ... 1-35 ...
            /* 36 number */{ STRAIGHT_36, BET_35_36, BET_33_36, BET_34_35_36, BET_32_33_35_36, BET_31_32_33_34_35_36,
                    TOP_2_TO_1, DOZEN_3_RD_12, HIGH_19_TO_36, RED, EVEN } };

    public BetPosition[] getPositions(int number) {
        BetPosition[] positions = numberToPositions[number];
        // some logic
        return positions;
    }
}


Where BetPosition is an enum with such a content:

public enum BetPosition {
    // ...
    STRAIGHT_32(96, ...),
    STRAIGHT_33(142, ...),
    STRAIGHT_34(52, ...),
    BET_1_2(53, ...),
    BET_4_5(55, ...),
    // ... long list of enum values

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

TODO..... investigate Guava code to have be sure that their code could follow that Check.

Issue is registered:
https://github.com/sevntu-checkstyle/sevntu.checkstyle/issues/453 

Saturday, February 15, 2014

New Check: Grammar in names and negative names restrictions

One more ambitions for Checkstyle - check grammar in method names and negative names restrictions.

Reason:
- developers do typos
- not all developers are good in English, and this nightmare to other team members who English by native
- Force developers to avoid negative name usage "isIncorrect()", "isNotIgnoredClass()"

Why negative name is bad approach - as it force to use that Negative Logic in other places.

Example:

Negative logic/name:
public boolean isNotCorrect() {...}

force other to have code like :
if (isNotCorrect())  // OK
if (!isNotCorrect())  // is NOT OK - it is unreadable!!!

So lets remove negative logic/name:
public boolean isCorrect() {...}

force other to have code like :
if (!isCorrect())  // it is OK
if (isCorrect())  // it is OK

BUT live is not that ideal sometime it is convenient to use negative logic or even more it is dependency from thirdparty code or legacy code.

That idea depends on grammar check in names base on vocabulary http://grammarist.com/usage/negative-prefixes/

we need options to check "boolean methods" "setter/getter" .... user might not need to test all names, option to check base on visibility - public/private/... .


http://www.liferay.com/community/wiki/-/wiki/Main/Javadoc+Guidelines#section-Javadoc+Guidelines-General+Guidelines , search for "Refer to parameters with "the", not "a" or "given"" - it will be good validation

Class: Initial and detailed description # "The first sentence of the initial class description starts with a verb (two verbs, in fact)."




If you run to this page and share idea with me, please let me know.

Thursday, January 23, 2014

How to change priority by filter in Zimbra web client

There is no such functionality in web client :(. But Zimbra support Priority setup, while composing, and display in mail list.

Please vote for issue against Zimbra web mail client: https://bugzilla.zimbra.com/show_bug.cgi?id=86080

Sunday, January 19, 2014

Proposals for Aqua mail-client android application

I use to have "Touchdown for smartphones" application to read mails for MSExchange mail server - perfect application and very customizable ! I loved it! But I moved to IMAP account and Touchdown does not support IMAP, so I have to switch from it to other application.

I did investigation of mail clients for Android and following application is really great and convenient for my workflow and usage.
Aqua mail client.

List of my proposals to make me forget about Touchdown:
1) New option: Do not mark Read on server.
2) How it is possible to filter UnRead mails in Folder
3) hide amount of mails in folder
4) new potion: hide Folder from list of synced Folders

Compress common part for project in Eclipse

Proposal to improve "Compress package names", list of features:

Compress package names: compress common part for project.

Checkstyle: ULC classes as static variables

Example of AvoidModifiersForTypesCheck in real code validation, implemented in sevntu.checkstyle 1.0.5 .

http://ulc.canoo.com/ulccommunity/Contributions/Extensions/GoodPractices.html

Static variables
Never keep instances of ULC classes in static variables (ULCIcons neither!). They cannot be shared between different sessions.

Post on ULC Canoo site that helps, at forum .

Monday, January 13, 2014

New Checkstyle idea: Appropriate Name Check

It is very ambition task but :) it will be good to have such Check to control typos and restrict non-English developers to write ease-to-read code.

Main focus on ensure that methods start  from verb, variable and Classes are nouns/adjectives (very difficult, separate vocabulary, ...... could be done as student diploma work).
As an option - Grammar validation for names of variables, methods, classes base on vocabulary - it will be very good experiment.

Attention for interesting Naming examples to consider for Class names and Boolean names:
http://checkstyle.sourceforge.net/availablechecks.html
AvoidStarImport - name started from verb.
allowByTrailComment - name started from verb - Boolean  variable , is there better name ?

so Check should be not that strict or rules for naming should be more complicated.

We could borrow spelling/grammar check from Eclipse.
Is there any other OSS library ?

Spell projects:
https://github.com/lyda/misspell-check



If you run to this page and share idea with me, please let me know.

Saturday, January 11, 2014

New Check idea: VariableNameLengthCheck


Reason to check code:
- code are not intuitive;
- easy to miss usage during code review small variables are easy to miss in big expressions
- hard to put mouse pointer in Eclipse to see usages ("Toggle Mark Occurrences"), description see item "Mark occurrences".
- in methods/c-tors names of arguments are used to auto-generate code in place of call. Reasonable names will give developers quick understanding how to use method/c-tor without reading Javadoc. Example is here, item "Content assist can insert argument names automatically".

How checkstyle could help here:
Task is possible to be done by means of Checkstyle, and it is clear style problem.
Checkstyle never did analyse of English grammar and meaning of variable names - that is not very simple task.
All we need there is teach checkstyle make abbreviations and short forms of full type names, Eclipse somehow do it ("Content assist for variable, method parameter and field name completions", "Less typing for assignments"), so could borrow some ideas from it.

Examples of code:

0) Is there way to calculate sort name from type ?
class ApplicationPermissions  == allowed short form => perm or permission or appPerm

1)
private String getFeature(Permissions p) {
String className = this.getClass().getPackage().getName();
String perspective = this.getClass().getName();
return className + ":" + p + ":" + perspective;
}

2) Comparison of same type variables. Looks like we need to skip that cases from validation.
As it will be hard to find proper names for both variables.

public static ApplicationPermissions getLess(ApplicationPermissions p1, ApplicationPermissions p2) {

int result = p1.compare(p2);

if (result == 0) {
return p1;
}
if (result > 0) {
return p2;
} else {
return p1;
}
}

3)  Is there any way  restrict odd names usage ? base on set of short names but forbidden to use , see example below:

ApplicationPermissions(String str, int level) {
this.str = str;
this.level = level;
}


4) Any ability to do exception for "Object o", is it reasonable ?
private void addPermissionEntry(String permAliase, Object o, ApplicationPermissions permission,
ApplicationPermissions defaultPermission) {
List<PermPair> permPairsList = null;

if (this.permMap.containsKey(permAliase)) {
permPairsList = this.permMap.get(permAliase);
} else {
permPairsList = new LinkedList<PermPair>();
this.permMap.put(permAliase, permPairsList);
}
permPairsList.add(new PermPair(o, permission, defaultPermission));
}

5) Allow usage f small names as they are FOR indexes.
for (int i = 0; i < samples.length; i++) {
if (font.canDisplayUpTo(samples[i][1]) == -1) {
supported[i] = true;
}
}
more complicated:
for (int i = 0; i < rows.length; i++) {
String rowstring = rows[i];
String[] values = rowstring.split("\t");
for (int j = 0; j < values.length; j++) {
String value = values[j];
if (startRow + i < rowCount && startCol + j < columnCount) {
dataTable.setValueAt(value, startRow + i, startCol + j);
}
}
}
and 
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
Assert.assertTrue(sh.isFilled(i, j));
}
}

6) clear sign one letter variable is assigned to good named variable/field

public PermPair(Object o, ApplicationPermissions p, ApplicationPermissions defaultPermission) {
this.feature = o;
this.permissions = p;
this.defaultPermissions = defaultPermission;
}

7) no excuse for short names for arguments as they could be used in code generation and other hint for Developers to let him skip reading of. See example from "6)"

8) We need to allow lover-cased CamelCase(short form) for variable from Classname, example:

Commandline cl = buildCommandLine(command);
executeCommandLine(cl, tableName, numberOfRecords);

9)

Wednesday, November 6, 2013

Checkstyle idea - require toString() method for Classes

toString() is required for classes that do logging as error to print context of them-self and around.

it might be reasonable to put in toString() only simple types fields that are provided by setXXXXX().

Johua Bloh idea about toString() for classes - Effective Java 2 book - "Item 10: Always override toString" - http://jtechies.blogspot.com/2012/07/item-10-always-override-tostring.html.

Having useful toString() make logging of context during error a simple and pleasant task.

Questions: What criteria we could follow to make a Check that will not force all Classes to have toString() on domains and critical for logging?

Override toString() everywhere is not practical, so we need figure out distinctive characteristics of Classes that have to do it.
- Class that is POJO
- ....

if somebody have ideas please share them on https://groups.google.com/forum/?hl=en#!forum/sevntu-checkstyle or https://groups.google.com/forum/?hl=en#!forum/checkstyle-devel

Monday, October 21, 2013

Checkstyle Check to detect System.out.println usage in java code

Examples of usage in code:
1.
import static java.lang.System.out;
...
out.println("hello!")

2.
System.out.println("hello");




Requirement:
- Analyse import for short name usage "import static java.lang.System.out;"

Possiblle name for Check: ForbidQualifierUsage

Options:
forbiddenFullQualifierNames : String List-  qualifier that we will search for (Example:"System.err.println")
ignoredClasses : Regex -  ignores (Example:"com.mycompany.console.Main")

Bad sides:
1) we can not distinguish methods by parameters so any user method with same name and without package usage will be false-positive if not all methods are investigated to detects overlap of static import in local declaration .

import static java.lang.System.setIn;


public static void setIn(InputStream in) {
    // just a method with similar signature that is compiled
    // if you comment out that method System.setIn will be used (tested in Intelij Idea)
}

public static void main(String... args) {
    setIn(null); // it is local if local method is defined
}

2) Any overloaded methods(same name but different parameters) will be false-positives or known limitations :) :

   System.out.println("hi", "hi")

https://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html#jls-7.5.3

It is permissible for one single-static-import declaration to import several fields or types with the same name, or several methods with the same name and signature. 
So JDK is OK with multiple imports by single static import, so overloaded identifiers are ok.


Resolution:
So it is not complete solution, kind of same level of false positives as RegExp search on code approach.
Could we close eyes on that false-positives?
do you have other ideas and proposal?
https://github.com/checkstyle/checkstyle/issues?q=is%3Aopen+is%3Aissue
Or discussion mail-list - https://groups.google.com/forum/#!forum/checkstyle-devel

Monday, October 7, 2013

Meetup with Scala IDEA plugin team leader


It was sad to see that JetBrains team leader use Windows for development:

How to create Checkstyle analog for Scala in IDEA IDE:

video will be there: https://thenewcircle.com/s

Tuesday, October 2, 2012

Thunderbird: Open link with different browser

I am just searching for convenient way to open links from Thunderbird in different Web browsers.

For FireFox there are good plugin Open With. I wish to have such addon in Thunderbird. I asked author   ... but no answer.

I in one year I searched the same problem and found a lot of requests/question for the same problem - :).

One of workaround that I use now - http://forums.opensuse.org/english/get-technical-help-here/applications/461076-how-do-i-get-thunderbird-open-links-google-chrome.html

Copy paste from this forum:

* Navigate to "Edit --> Preferences --> Advanced" in the Thunderbird menus and click on the "Config Editor" button.
    * Search for the following three entries:
          o network.protocol-handler.warn-external.http
          o network.protocol-handler.warn-external.https
          o network.protocol-handler.warn-external.ftp
    * Set the value of each of these three entries to true (you can do this by double-clicking on each entry, then close the "about:config" window and click "OK" on the "Thunderbird Preferences" window).