oop - Is this a good practice to use the "default" Java access to hide classes and methods from client -


  • in case of classes:

if use factory method we'll have return created implementation type of implemented interface.

public class factory {    public product getproduct() {     return new producta();   } } 

public interface product { } 

class producta implements product { } 

to avoid client's ability cast returned product concrete implementation of product{a, b, c... etc.} have to:

  1. package client's , factory's code separately (let's com.example.client , com.example.factory)
  2. declare concrete implemantations default ("package") access (visible factory, not visible client)

    package com.example.client;     ...     public class client {       public static void main(string[] args) {         product = new factory().getproduct();         producta = (producta) i; // type of producta isn't visible.       }     } 
  • in case of methods:

for example need use same factory hidden method

public class factory {    public product getproduct() {     return new producta();   }    product[] getcreatedproducts() {     ...   } } 

i see 2 problems here:

  • bad package structure: hidden classes , methods must in 1 package calling code.
  • bad code: less intuitive , understandable. it's easy break replacement of java files package.

the "default" access not guarantee of anything, since rogue programmer can declare class in package. also, regardless of package structure, in java, can "instance of" check, , downcast "instance of" type. so, if goal prevent downcasting whatsoever, must use private keyword. example, can declare concrete implementations of product interface private static or anonymous inner classes within factory. indeed, in bloch's "how design api" article, makes point should "minimize accessibility of everything."

that said, think you're being little paranoid here. matter if downcasts? code write can misused, , if include well-documented factory have provided clear information how use api properly. also, if build real factory method takes arguments , has clear method names, opposed toy factory example takes no arguments, think you'll find you're broadcasting publicly relevant part of what's being created anyway.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -