开发者

static constants return instance of specific class in Flex?

开发者 https://www.devze.com 2022-12-28 08:10 出处:网络
So here\'s what 开发者_JAVA技巧I mean. Let\'s say I have a class ErrorMessages which holds all my error messages as static constants. So I could access them like ErrorMessages.PASSWORD_INVALID or Erro

So here's what 开发者_JAVA技巧I mean. Let's say I have a class ErrorMessages which holds all my error messages as static constants. So I could access them like ErrorMessages.PASSWORD_INVALID or ErrorMessage.PASSWORD_TOO_SHORT. I want to know if it is possible to have separate classes that hold subset of these constants and access them like ErrorMessages.PASSWORD.INVALID or ErrorMessages.PASSWORD.TOO_SHORT, etc. This way I can more structured static structure and makes it much easier to use autocomplete. I tried few different ways and couldn't figure out if this was possible..


Declare them as const Objects in the static class - you won't get them in auto complete though.

public class ErrorMessages
{
  public static const PASSWORD:Object = {
     INVALID:"invalid password",
     TOO_SHORT:"minimum 6 chars required",
     TOO_LONG:"100 chars: r u sure?"
  };
  public static const FILE:Object = {
     NOT_FOUND:"No such file",
     READ_ONLY:"it is readonly",
     SOMETHING_ELSE:"something else"
  };
}

trace(ErrorMessages.PASSWORD.INVALID);

If auto complete is important, create a dedicated com.domain.errors package and declare different classes for different categories of errors (like PASSWORD, FILE etc) within that package. Now declare public static constants inside those classes as appropriate.


or if you want to keep a single class, you can define classes, inside your Error class. You might would like to have those text coming from properties file. So, you can make use of resourceManager instance and get the text from specific resource bundle.

-- http://riageeks.com


Here's what I end up doing

package com.domain.data.type {
  public class ErrorMessages {
    public static function get PASSWORD:PasswordErrorMessages { return new PasswordErrorMessages(); }
    }
}
class PasswordErrorMessages {
  public function get INVALID():String  { return "invalid password"; }
}

This way I can get the behavior I wanted: ErrorMessages.PASSWORD.INVALID with autocomplete. It's not as clean as I'd like it to be.. but I guess this will do.

0

精彩评论

暂无评论...
验证码 换一张
取 消